【发布时间】:2019-03-01 03:28:04
【问题描述】:
我有一个数组定义如下:
const myArr: (MyType | null)[] = [];
还有一个函数如下:
const myFunc = (myObj: MyType) => /* do sth */;
如果我通过非 null 过滤 myArr,然后尝试使用 myFunc 进行映射,我得到一个编译错误,因为 MyType | null 不能分配给 MyType。我明白为什么会这样,但这是过滤器和地图代码:
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'.
}
}
如果我转换过滤器的结果:
const notNullResults = this.myArray.filter(str => str !== null) as string[]
它编译得很好,但我不喜欢这样强制转换。 TypeScript 有没有办法推断过滤后的数组具有不同的类型定义?
【问题讨论】:
-
我不认为你会解决这个问题。
-
This open suggestion 会让 TypeScript 自动推断
str => str !== null是一个类型保护。
标签: javascript typescript