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?
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.
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.
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() .
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;
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 |
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With