Debugging Errors: Narrowing Types
This lesson walks through the debugging of a compile error that can be addressed by appropriate type narrowing.
We'll cover the following...
Overview #
Another error that we’ll look at is an example of a situation when TypeScript is not able to narrow the type of a variable, even though it might be obvious from the perspective of the programmer.
Press + to interact
interface Person { name: string; employer?: string; };function getEmployers(persons: Person[]): string[] {return persons.filter(person => person.employer !== undefined).map(person => person.employer); // 🔴 Error!}
The above code will result in the following error message.
Type '(string | undefined)[]' is not assignable to type 'string[]'.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.ts(2322)
Digging deeper
Let’s break down the error message.
Type
...