简体   繁体   English

typescript 中的过滤器出现“(字符串 | null)[]”错误不可分配

[英]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);

Playground link 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 输入&#39;字符串| null&#39; 不能分配给类型 &#39;string | TypeScript 的未定义错误 - Type 'string | null' is not assignable to type 'string | undefined error with TypeScript Typescript、JSON.parse 错误:“类型 'null' 不可分配给类型 'string'。” - Typescript, JSON.parse error: "Type 'null' is not assignable to type 'string'." TypeScript 类型'字符串 | null' 不可分配给类型 'string' - TypeScript Type 'string | null' is not assignable to type 'string' Typescript 错误类型“null”不可分配给类型 - Typescript Error Type 'null' is not assignable to type TypeScript 错误:类型“字符串”不可分配给排版类型 - TypeScript error: Type 'string' is not assignable to type for Typography 打字稿类型&#39;字符串&#39;不可分配给类型“错误 - Typescript Type ‘string’ is not assignable to type" error Typescript - 'string | 类型的参数 (string | null)[]' 不能分配给“string”类型的参数 - Typescript - Argument of type 'string | (string | null)[]' is not assignable to parameter of type 'string' Typescript:字符串可分配给 {} 类型 - Typescript: string is assignable to {} Type 'string | 类型的参数 undefined' 不可分配给“string”类型的参数 - TypeScript 错误 - Argument of type 'string | undefined' is not assignable to parameter of type 'string' - TypeScript error 打字稿:不可分配给键入错误 - Typescript: is not assignable to type error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM