npmtypescript95% confidence\u2191 635

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?

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/ada55bb85c778802104fad7fba28dade4fb1df78d720d0acfc6440af9d071f1a
hash \u00b7 ada55bb85c778802104fad7fba28dade4fb1df78d720d0acfc6440af9d071f1a
TypeScript: Type&#160;&#39;string&#160;|&#160;undefined&#39;… — DepScope fix | DepScope