awvalenti
awvalenti

Reputation: 2013

Contional type to filter methods of object/class in TypeScript

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

Answers (1)

awvalenti
awvalenti

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

Related Questions