从数组过滤未定义时的打字稿类型错误

时间:2019-10-25 13:52:19

标签: typescript

我想像这样从数组中过滤未定义的项目

type Kind = 'foo' | 'bar'

const someFunc = () : Array<{ kind: Kind, name: string }> => {
    return [{ kind: 'foo', name: 'a' }].filter(x => x !== undefined)
}

给出以下类型错误:

Type '{ kind: string; name: string; }[]' is not assignable to type '{ 
kind: Kind; name: string; }[]'.
Type '{ kind: string; name: string; }' is not assignable to type '{ 
kind: Kind; name: string; }'.
Types of property 'kind' are incompatible.
  Type 'string' is not assignable to type 'Kind'.

为什么会失败,以及如何处理?

2 个答案:

答案 0 :(得分:1)

因为TypeScript从[{ kind: 'foo', name: 'a' }]推断出数组的类型。如果您告诉它数组的类型是什么,它将变得更快乐。 :)

type Kind = 'foo' | 'bar'

const someFunc = (): Array<{ kind: Kind; name: string }> => {
    const array: Array<{kind: Kind; name: string}> = [{ kind: 'foo', name: 'a' }];
    return array.filter(x => x !== undefined)
}

答案 1 :(得分:1)

您可以创建一个新变量来声明kind的类型。这是因为TypeScript推断这种类型是字符串。

type Kind = "foo" | "bar"

const someFunc = (): Array<{kind: Kind, name: string}> => {
    const kind: Kind = 'foo'
    return [{ kind, name: 'a' }].filter(x => x !== undefined)
}