Alex Craft
Alex Craft

Reputation: 15386

TypeScript guard for nullable type doesn't work

Why guard for nullable type doesn't work in this case?

interface Person { name?: string }
let alex = {} as Person

function welcome(person: { name: string }) {}

if (alex.name != null) {
  s = alex.name          // Works nicely, no error here, 
                         // it knows that alex.name isn't null

  welcome(alex)          // Wrongly complains here 
                         // that `alex.name` could be null
}

You need to enable strictNullCheck compiler option.

Upvotes: 1

Views: 497

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164357

Regardless of whether or not alex.name is null, the types { name?: string } and { name: string } aren't compatible.

You can do this:

function hasName(person: Person): person is { name: string } {
    return person.name != null;
}

if (hasName(alex)) {
    welcome(alex);
}

Edit

It might be an overkill, but that's how type guards work.
You can of course just type assert it:

welcome(alex as { name: string });

Upvotes: 4

Related Questions