Typescript: Type 'String | Undefined' Is Not Assignable to Type 'String'
When I Make Any Property of an Interface Optional, and While Assigning Its Member to Some Other Variable Like This: Interface Person { Name? : String, Age?...
When I make any property of an interface optional, and while assigning its member to some other variable like this:
interface Person {
name?: string,
age?: string,
gender?: string,
occupation?: string,
}
function getPerson() {
let person = <Person>{name:"John"};
return person;
}
let person: Person = getPerson();
let name1: string = person.name; // <<< Error here
I get an error like the following:
TS2322: Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
How do I get around this error?
17 Answers
You can now use the non-null assertion operator that is here exactly for your use case.
It tells TypeScript that even though something looks like it could be null, it can trust you that it's not:
let name1:string = person.name!;
// ^ note the exclamation mark here
To avoid the compilation error I used
let name1:string = person.name || '';
And then validate the empty string.
I know this is a kinda late, but another way besides yannick's answer to use ! is to cast it as string thus telling TypeScript: I am sure this is a string, thus converting it.
let name1:string = person.name;//<<<Error here
to
let name1:string = person.name as string;
This will make the error go away, but if by any chance this is not a string you will get a run-time error... which is one of the reasons we are using TypeScript to ensure that the type matches and avoid such errors at compile time.
As of TypeScript 3.7 you can use nullish coalescing operator ??. You can think of this feature as a way to “fall back” to a default value when dealing with null or undefined
let name1:string = person.name ?? '';
The ?? operator can replace uses of || when trying to use a default value and can be used when dealing with booleans, numbers, etc. where || cannot be used.
As of TypeScript 4 you can use ??= assignment operator as a ??= b which is an alternative to a = a ?? b;
By your definition Person.name can be null but name1 cannot.
there are two scenarios:
Must Read
Person.name is never null
tell the compiler your are sure the name is not null by using !
let name1: string = person.name!;