Reputation: 974
Given a utility ExtractKeysOfType
that allows to retrieve only key of a type/interface that match a target and the Pick
type i can easily extract function from a given type/interface.
What I want to accomplish is to extract only the async function (and not all signatures) from the base type.
Any clue on how to achieve that ?
type ExtractKeysOfType<T, Target> = {
[K in keyof T]: T[K] extends Target ? K : never
}[keyof T]
type Type = {
prop: boolean
fn (): boolean
fn (): Promise<boolean>
}
type OnlyFunc = Pick<
Type,
ExtractKeysOfType<Type, (...as: any) => any>
> // {fn (): {boolean; Promise<boolean>}
type OnlyAsync = ??? // Someway to build type such as OnlyAsync: {fn (): Promise<boolean>}
Upvotes: 2
Views: 673
Reputation: 120450
Drawing on this answer as inspiration, we can define an OnlyAsync
type using mapped and conditional types as follows:
// finds keys of Promise returning function members
type PromiseFuncKeys<T> = {
[K in keyof T]: T[K] extends ((...args: any[]) => Promise<any>) ? K : never;
}[keyof T]
// so we can Pick them
type OnlyAsync<T> = Pick<T, PromiseFuncKeys<T>>;
Here's another answer that should shed some light on what's going on here.
Upvotes: 2