Typescript: Type 'string | undefined' is not assignable to type 'string'

When I make any property of an interface optional, I get an error like the following while assigning its member to some other variable:

    TS2322: Type 'string | undefined' is not assignable to type 'string'.
    Type 'undefined' is not assignable to type 'string'.
    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 

How do I get around this error?


Solution 1:

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  

Solution 2:

To avoid the compilation error I used

let name1:string = person.name || '';

And then validate the empty string.

Solution 3:

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.