0

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?

2

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.