. Advertisement .
. Advertisement .
Hello everyone! I’m back and continuing the series of lessons on dealing with errors that programmers often encounter. And today is the error “Typescript Type ‘string’ is not assignable to type“. Have you ever encountered this situation? If you still can’t handle it, don’t worry, this article will help you. Let’s follow along!
What is “Typescript Type ‘string’ is not assignable to type”?
The following is an example of an error program illustrating the above scenario.
This is the command line the coder used in the fruit.ts . file
export type Fruit = "Orange" | "Apple" | "Banana"
Then they continue to declare fruit.ts file in another file like below:
myString:string = "Banana"; myFruit:Fruit = myString;
After running this command, they got the error “Type ‘string’ is not assignable to type ‘”Orange” | “Apple” | “Banana”‘:
myFruit = myString;
When you declare: export type Fruit = “Orange” | “Apple” | “Banana”
That is, now the “Fruit” you declare will only include the components “Orange”, “Apple” and “Banana”. That is, you are just declaring more for the string Fruit or assigning it more. So the string will not return the result you want. because it won’t be able to expand “Orange” | “Apple” | “Banana”. Besides, this is also a feature when you declare with strings, between string declaration elements, you must use this character |.
For the above situation, we suggest that you try to pass it like below:
export type Fruit = "Orange" | "Apple" | "Banana"; let myString: string = "Banana"; let myFruit: Fruit = myString as Fruit;
Also another idea is that you can apply const, It seems to work fine in this situation:
let fruit = "Banana" as const;
To summarize, in the above article, we have given you a solution when you encounter “Typescript Type ‘string’ is not assignable to type“. This is a pretty common mistake when working with strings. Hope you get your problem resolved and get the project up and running again soon. If there are any difficulties, please contact us immediately for the fastest support.
In addition, our website is always updated with new articles for programmers. Follow along and leave comments on articles you find useful. That will help us build the website more and more completely. Thank you for reading and see you soon!