Reputation: 2013
How to filter properties of an object to get only those that are methods?
const obj = {
a: 1,
b: 'text',
c: () => null,
d: (arg0: number) => arg0 + 1
}
type AllKeys = keyof typeof obj // 'a' | 'b' | 'c' | 'd'
// type OnlyMethodsKeys = (???) // 'c' | 'd'
Upvotes: 0
Views: 35
Reputation: 2013
From https://github.com/microsoft/TypeScript/pull/21316:
type FunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? K : never }[keyof T];
type FunctionProperties<T> = Pick<T, FunctionPropertyNames<T>>;
type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>;
So we can do:
type OnlyMethodsKeys = FunctionPropertyNames<typeof obj> // 'c' | 'd'
Works for classes, too:
class C {
a = 1
b = 'text'
c() {
return null
}
d(arg0: number) {
return arg0 + 1
}
}
type AllKeys = keyof C // 'a' | 'b' | 'c' | 'd'
type OnlyMethodsKeys = FunctionPropertyNames<C> // 'c' | 'd'
Upvotes: 1