Is there a way for typescript to infer that null values are no longer possible in an array?

I have an array defined as follows:

const myArr: (MyType | null)[] = [];

And a function as follows:

const myFunc = (myObj: MyType) => /* do sth */;

If I filter myArr by not null, then try to map with myFunc, I get a compilation error because MyType | null is not assignable to to MyType. I understand why this is happening, but this is the filter and map code:

class MyClass {

  private myArray: (string | null)[] = [];
  
  myFunc = (str: string) => str.toUpperCase();

  myOtherFunc = () => {
    this.myArray
      .filter(str => str !== null)
      .map(this.myFunc); // Type 'string | null' is not assignable to type 'string'.
  }

}

If I cast the result of filter:

const notNullResults = this.myArray.filter(str => str !== null) as string[]

It compiles fine, but I don't like force casting like that. Is there a way for TypeScript to infer that the filtered array has a different type definition?

Upvotes: 1

Views: 2003

Answers (1)

Uzi
Uzi

Reputation: 2634

Yes, you need a type guard.

const notNullResults = this.myArray.filter((str): str is string => str !== null) // string[]

note that we're using the is operator along with the built-in generic string type to indicate we're expecting only strings

Upvotes: 3

Related Questions