【发布时间】:2020-03-11 22:21:51
【问题描述】:
我想过滤条件类型的数组并具有正确的返回类型。比如下面的代码:
const foo = {
type: "foo" as const,
foo: 123
}
const bar = {
type: "bar" as const,
bar: 123
}
const arr = [foo, bar]
const filteredArr = arr.filter(val => val.type === 'foo');
filteredArr.map(val => {
val.foo //Typescript blows up! Property foo does not exist on type
})
我想出的唯一解决方案是转换过滤后的数组:
type Foo = typeof foo;
const filteredArr = arr.filter(val => val.type === 'foo') as Foo[];
但似乎应该有一种方法打字稿足够聪明,可以推断出数组已被过滤到仅Foo[]。
也许用户定义的类型保护有一些棘手的用法?
【问题讨论】:
标签: arrays typescript