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?
CodePudding user response:
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.
CodePudding user response:
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
}