'Typescript: Type 'string' not assignable to a string of fixed values
I am new to typescript.I am working on a backed that uses Express, Node and Typescript. I have an object that has type:
interface Fruit {
FruitType: "Citrus" | "Melon" | "Tropical"
FruitName: string
}
I am creating a new instance of Fruit where I am reding the fruit type from JSON file and populating it
const config = readFromFile()
const myFruit:Fruit ={
FruitName: config.fruitName,
FruitType: config.fruitTYPE
}
This gives an error Type 'string' not assignable to type "Citrus" | "Melon" | "Tropical". I understand I am getting this error because I am assigning an unknown string instead of an Enum value. I am assuming the solution is to somehow check if the fruit type is one of the values before assigning it to the FruitType object. How do I fix this error?
Solution 1:[1]
You need to cast it.
type fruitCategories = "Citrus" | "Melon" | "Tropical"
interface Fruit {
FruitType: fruitCategories
FruitName: string
}
Now, you have the fruitCategories that sets the fruitType.
const config = readFromFile()
const myFruit:Fruit ={
FruitName: config.fruitName,
FruitType: config.fruitTYPE as fruitCategories // you need to tell the complier
}
So, you need to cast the type from string and tell the complier that this should be of type fruitCategories or anyname you want.
Solution 2:[2]
First you need to cast the value and use it.
type fruitType= "Citrus" | "Melon" | "Tropical"
interface Fruit {
FruitType: fruitType
FruitName: string
}
const config = readFromFile()
const myFruit : Fruit = {
FruitName: config.fruitName,
FruitType: config.fruitTYPE as fruitType // Cast the config.fruitTYPE to fruitType
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Apoorva Chikara |
| Solution 2 | Ganesan C |
