How to fix the “Type ‘string’ is not assignable to type” error with TypeScript?

Sometimes, we want to fix the “Type ‘string’ is not assignable to type” error with TypeScript.

In this article, we’ll look at how to fix the “Type ‘string’ is not assignable to type” error with TypeScript.

How to fix the “Type ‘string’ is not assignable to type” error with TypeScript?

To fix the “Type ‘string’ is not assignable to type” error with TypeScript, we should cast the variable to the type we want.

For instance, we write

export type Fruit = "Orange" | "Apple" | "Banana";
const myString: string = "Banana";
const myFruit: Fruit = myString as Fruit;

to create the Fruit literal type.

Then we create the myString string variable that’s set to 'Banana'.

And then we create the myFruit variable of Fruit type that’s assigned to myString after we cast it to a Fruit.

The TypeScript compiler will check if the value of myFruit match any of the values listed in Fruit after casting.

Conclusion

To fix the “Type ‘string’ is not assignable to type” error with TypeScript, we should cast the variable to the type we want.