我需要根据特定属性值的undefined
状态过滤array.为了实现这一点,我使用了一个类型谓词来强制filter
结果的类型.数组中的值包含一个必需属性,该属性在类型谓词的类型中是可选的.
使用以下示例(TS Playground):
interface OptionalModel {
prop?: string;
otherProp: number;
}
interface RequiredModel {
prop: string | undefined;
otherProp: number | undefined;
}
const array: RequiredModel[] = [];
// How to filter/convert `array` to an array of `OptionalModel` ?
const filterKO = array.filter((value): value is OptionalModel => typeof value.otherProp !== 'undefined'); // ✗
filterKO
的声明中有一个错误.TS在类型谓词中表示OptionalModel
:
A type predicate's type must be assignable to its parameter's type.
Type 'OptionalModel' is not assignable to type 'RequiredModel'.
Property 'prop' is optional in type 'OptionalModel' but required in type 'RequiredModel'.(2677)
由于OptionalModel
中的可选属性,不可能使用类型谓词;但是,由于RequiredModel
中可能有undefined
个其他属性,因此不可能将array
直接用作OptionalModel[]
.
我怎么才能实现过滤,把filterKO
种缩小到OptionalModel[]
种呢?