您的FilterKeys<T, U>
的行为类似于the Extract
utility type,因为它 Select 可以分配给另一种类型的东西.您可以通过 Select 可将not分配给另一类型的对象来获得所需的行为,使其行为类似于the Exclude
utility type.只需切换相关conditional type的真和假分支:
type ExcludeKeys<T, U> = {
[K in keyof T]: T[K] extends U ? never : K;
}[keyof T];
然后,您可以将ExcludeKeys
与() => Promise<unknown>
一起使用,以仅获取其值不是Promise
返回函数的键:
type O = {
A: () => void;
B: () => Promise<string>;
};
type Keys = ExcludeKeys<O, () => Promise<unknown>>;
// ^? type Keys = "A"
请注意,() => Promise<unknown>
比() => Promise<void>
更宽,因此将捕获所有返回Promise
的函数.
当然,这也将为您提供非函数,因此,如果您需要保留值类型为不返回promise 的函数的only个键,您将需要两个过滤器的组合:
type ExtractKeys<T, U> = {
[K in keyof T]: T[K] extends U ? K : never;
}[keyof T];
type O = {
A: () => void;
B: () => Promise<void>;
C: string // we don't want this one either
};
type Keys = ExcludeKeys<Pick<O, ExtractKeys<O, Function>>, () => Promise<unknown>>;
// ^? type Keys = "A"
或者,您可以构建一个组合过滤器:
type ExtractExcludeKeys<T, Y, N> = {
[K in keyof T]: T[K] extends N ? never : T[K] extends Y ? K : never;
}[keyof T]
type Keys = ExtractExcludeKeys<O, Function, () => Promise<unknown>>;
// ^? type Keys = "A"
Playground link to code个