[英]filter in typescript got error of '(string | null)[]' is not assignable
I have an array of object, one of the property has a null value, I used filter to remove it, but typescript give me warning null is not assignable? I have an array of object, one of the property has a null value, I used filter to remove it, but typescript give me warning null is not assignable? since filter will never return null why typescript give me such an error?
因为过滤器永远不会返回 null 为什么 typescript 给我这样的错误?
const data = [
{
id: "123"
},
{
id: "456"
},
{
id: null
}
];
const d2: string[] = data.map((d) => d.id).filter((o) => o);
console.log(d2);
demo https://codesandbox.io/s/gallant-water-vio56?file=/src/index.ts:0-165演示https://codesandbox.io/s/gallant-water-vio56?file=/src/index.ts:0-165
Typescript can't figure out that .filter((o) => o)
will narrow the types of the array, not without some help. Typescript 无法确定
.filter((o) => o)
会缩小数组的类型,这并非没有帮助。 You can define a custom type guard and use that though.您可以定义自定义类型保护并使用它。 For example:
例如:
function notNull<T>(val: T | null): val is T {
return val !== null;
}
const d2 = data.map((d) => d.id).filter(notNull); // d2 is a string[]
Or an inline version that only works with strings:或仅适用于字符串的内联版本:
const d2 = data.map(d => d.id).filter((o): o is string => !!o);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.