Skip to content

Instantly share code, notes, and snippets.

@matthew-dean
Last active October 2, 2023 17:42
Show Gist options
  • Save matthew-dean/9267ab91b0c701cfb956f7f0c1549b55 to your computer and use it in GitHub Desktop.
Save matthew-dean/9267ab91b0c701cfb956f7f0c1549b55 to your computer and use it in GitHub Desktop.
Getting all methods of an object - TypeScript version
type Obj = Record<any, any>
const isGetter = (x: Obj, name: string) => Boolean((Object.getOwnPropertyDescriptor(x, name) ?? {})?.get)
const isFunction = (x: Obj, name: string) => typeof x[name] === 'function'
const deepFunctions = (x: Obj): string[] =>
(x && x !== Object.prototype &&
Object.getOwnPropertyNames(x)
.filter(name => isGetter(x, name) || isFunction(x, name))
.concat(deepFunctions(Object.getPrototypeOf(x)) || [])) || []
const distinctDeepFunctions = (x: Obj) => Array.from(new Set(deepFunctions(x)))
const getMethods = (obj: Obj) => distinctDeepFunctions(obj).filter(
name => name !== 'constructor' && !~name.indexOf('__'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment