Shankze
Shankze

Reputation: 4099

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?

Upvotes: 0

Views: 1061

Answers (2)

Ganesan C
Ganesan C

Reputation: 277

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
    }

Upvotes: 0

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

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.

Upvotes: 2

Related Questions