我有一个类型为Array<[string, unknown]>
的数组。我想通过.type
属性的元组的第二个元素来过滤此数组。
应用过滤器后,我无法得出能够正确给出输出数组正确类型的类型预测。
我已经尝试过了:
const isSchemaProp = (entry: unknown): entry is [string, { type: string }] => {
const [, value] = entry as [string, { type: sting }];
return value.type !== undefined;
};
const newArr = arr.filter(entry => isSchemaProp(entry)) // Second element of each element is still unknown
答案 0 :(得分:4)
filter
的回调函数参数必须是具有谓词类型的函数,以便更改filter
的返回类型。从回调内部调用类型断言是不够的。
const newArr = arr.filter(
(entry): entry is [string, { type: string }] => {
return isSchemaProp(entry)
}
)
或者,由于类型谓词具有此功能,因此您可以直接将其传递:
const newArr = arr.filter(isSchemaProp)