Here’s what I have in fruit.ts
JavaScript
x
2
1
export type Fruit = "Orange" | "Apple" | "Banana"
2
Now I’m importing fruit.ts in another typescript file. Here’s what I have
JavaScript
1
4
1
myString:string = "Banana";
2
3
myFruit:Fruit = myString;
4
When I do
JavaScript
1
2
1
myFruit = myString;
2
I get an error:
Type ‘string’ is not assignable to type ‘”Orange” | “Apple” | “Banana”‘
How can I assign a string to a variable of custom type Fruit?
Advertisement
Answer
Update
As mentioned in @Simon_Weaver’s answer, since TypeScript version 3.4 it’s possible to assert it to const
:
JavaScript
1
2
1
let fruit = "Banana" as const;
2
Old answer
You’ll need to cast it:
JavaScript
1
5
1
export type Fruit = "Orange" | "Apple" | "Banana";
2
let myString: string = "Banana";
3
4
let myFruit: Fruit = myString as Fruit;
5
Also notice that when using string literals you need to use only one |