Skip to content
Advertisement

Typescript Type ‘string’ is not assignable to type

Here’s what I have in fruit.ts

JavaScript

Now I’m importing fruit.ts in another typescript file. Here’s what I have

JavaScript

When I do

JavaScript

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

Old answer

You’ll need to cast it:

JavaScript

Also notice that when using string literals you need to use only one |

Advertisement