我编写了一个filterObject
函数,接受一个对象和一个回调函数作为该函数的输入.对于回调函数,我描述了类型和类型保护.但由于某些原因,类型保护不能正常工作.
以下是功能代码
type Entry<T> = {
[K in keyof T]: [K, T[K]];
}[keyof T];
const filterObject = <T extends { [key: PropertyKey]: T[keyof T] }, S extends T>(
obj: T,
callback: (val: Entry<T>) => val is Entry<S>,
) => {
return Object.entries(obj).filter(callback);
};
这里我用类型保护调用filterObject
函数
type A = {
a?: number;
b: number;
};
const obj: A = {
a: 1,
b: 2,
};
const data = filterObject(obj, (val): val is Entry<Required<A>> => {
return true;
});
执行filterObject
功能后.
变量data
的类型是[string, number | undefined][]
,但理论上应该是[string, number][]
.
由于回调类型保护设置为(val is Entry<Required<A>>)
,Required<A>
删除了可选标志(?)从对象字段
Expected behavior: the variable data
type is [string, number][]
Actual behavior: the variable data
type is [string, number | undefined][]
链接到playground