问题描述
我有一个类型为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
解决方法
filter
的回调函数参数必须是具有谓词类型的函数,以便更改filter
的返回类型。从回调内部调用类型断言是不够的。
const newArr = arr.filter(
(entry): entry is [string,{ type: string }] => {
return isSchemaProp(entry)
}
)
或者,由于类型谓词具有此功能,因此您可以直接将其传递:
const newArr = arr.filter(isSchemaProp)