HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

TypeScript Type 'string' is not assignable to type

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typescriptassignablenotstringtype

Problem

Here's what I have in file fruit.ts:

export type Fruit = "Orange" | "Apple" | "Banana"


Now I'm importing fruit.ts in another TypeScript file. Here's what I have

myString:string = "Banana";

myFruit:Fruit = myString;


When I do

myFruit = myString;


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?

Solution

Update

As mentioned in @Simon_Weaver's answer, since TypeScript version 3.4 it's possible to assert it to const:

let fruit = "Banana" as const;


Old answer

You'll need to cast it:

export type Fruit = "Orange" | "Apple" | "Banana";
let myString: string = "Banana";

let myFruit: Fruit = myString as Fruit;


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

Code Snippets

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

let myFruit: Fruit = myString as Fruit;

Context

Stack Overflow Q#37978528, score: 656

Revisions (0)

No revisions yet.