Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Created August 6, 2021 11:54
Show Gist options
  • Save karol-majewski/408644df3fe8c1a5a20289e645c3c6c7 to your computer and use it in GitHub Desktop.
Save karol-majewski/408644df3fe8c1a5a20289e645c3c6c7 to your computer and use it in GitHub Desktop.
Extract methods/function properties from a type in TypeScript
type AnyFunction = (...args: any[]) => any;
type FunctionPropertyOf<T> = {
[P in keyof T]: T[P] extends AnyFunction ? P : never;
}[keyof T];
type MethodOf<T> = {
[P in keyof T]: T[P] extends (this: ThisType<T[P]>, ...args: any[]) => any ? P : never;
}[keyof T];
type Foo = MethodOf<RemoveIndexSignature<Storage>> // "clear" | "getItem" | "key" | "removeItem" | "setItem"
type Bar = FunctionPropertyOf<RemoveIndexSignature<Storage>> // "clear" | "getItem" | "key" | "removeItem" | "setItem"
/**
* https://stackoverflow.com/a/66252656/10325032
*/
type RemoveIndexSignature<T> = {
[P in keyof T as string extends P ? never : number extends P ? never : P]: T[P];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment