Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Type 'string' is not assignable to type

Here's what I have in 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?

like image 940
user6123723 Avatar asked Oct 10 '22 09:10

user6123723


People also ask

How do I fix undefined string is not assignable to type string?

The "Type 'string | undefined' is not assignable to type string" error occurs when a possibly undefined value is assigned to something that expects a string . To solve the error, use the non-null assertion operator or a type guard to verify the value is a string before the assignment.

Is not assignable to parameter of type string?

The error "Argument of type string | undefined is not assignable to parameter of type string" occurs when a possibly undefined value is passed to a function that expects a string . To solve the error, use a type guard to verify the value is a string before passing it to the function.

How do you assign an undefined string to a TypeScript?

The typescript compiler performs strict null checks, which means you can't pass a string | undefined variable into a method that expects a string . To fix this you have to perform an explicit check for undefined before calling luminaireReplaceLuminaire() .


Video Answer


2 Answers

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 |

like image 533
Nitzan Tomer Avatar answered Oct 12 '22 11:10

Nitzan Tomer


Typescript 3.4 introduced the new 'const' assertion

You can now prevent literal types (eg. 'orange' or 'red') being 'widened' to type string with a so-called const assertion.

You will be able to do:

let fruit = 'orange' as const;  // or...
let fruit = <const> 'orange';

And then it won't turn itself into a string anymore - which is the root of the problem in the question.

You can also do it on a whole object:

let animals = [ { species: 'dog' }, { species: 'cat' } ] as const;

type firstAnimal = (typeof animals)[0]['species'];  // string literal 'dog'

Bonus Tip: You can also use <const> false or <const> true to represent a boolean that must be true or false. This can be useful in discriminated unions sometimes. You'll know it when you see it.

like image 183
Simon_Weaver Avatar answered Oct 12 '22 09:10

Simon_Weaver