TypeScript: Type 'string | undefined' is not assignable to type 'string'
Full error message
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?Solutionsource: stackoverflow \u2197
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
API access
Get this solution programmatically \u2014 free, no authentication.
curl https://depscope.dev/api/error/ada55bb85c778802104fad7fba28dade4fb1df78d720d0acfc6440af9d071f1ahash \u00b7 ada55bb85c778802104fad7fba28dade4fb1df78d720d0acfc6440af9d071f1a