Reputation: 93
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