Skip to content

Instantly share code, notes, and snippets.

@arielshaqed
Last active October 26, 2022 12:23
Show Gist options
  • Save arielshaqed/e972eae06721fd85b2e70e5b2ab07680 to your computer and use it in GitHub Desktop.
Save arielshaqed/e972eae06721fd85b2e70e5b2ab07680 to your computer and use it in GitHub Desktop.
Extract keys of methods of TypeScript type
// https://www.typescriptlang.org/play/#code/C4TwDgpgBAshwAsD2ATA0hEBnA8gJwDkIA3CPAHgBUA+KAXigG8AoKNqAbTSgEsA7KAGtMSAGZRKAXQBcErpKgQAHsAh8UWKADEArnwDGwHkgEB+KN1l8SZANzMAvs1CRY8ZOkxYqtBnESoGNj4RKQUNBzCIGISkvbM-Kp4ogCG+tAAkkys7HxWOgC2AEZ2OWyiABQp+cVkAJSyWMB4-ADm9uxQrRUNUMRIPCj2Ti7QWvRuAZ7Y5BnUtmwA9ItQAESiq1AAPmutq8xAA
type MethodKeysOrNever<T> = {
[K in keyof T]: T[K] extends Function ? K : never;
}
type MethodKeys<T> = MethodKeysOrNever<T>[keyof T];
@arielshaqed
Copy link
Author

arielshaqed commented Jan 23, 2020

MethodKeysOrNever transforms T into a class with value types equal either to the key (for method keys) or never. Now MethodKeys extracts the value types for all these keys. But never drops out of union types, leaving just the key types of T that map to a function type.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment