Skip to content

Instantly share code, notes, and snippets.

@blixt
Created November 22, 2018 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blixt/456867b9fafc3b480fd244341c13fea8 to your computer and use it in GitHub Desktop.
Save blixt/456867b9fafc3b480fd244341c13fea8 to your computer and use it in GitHub Desktop.
Did you know TypeScript's type system is Turing complete?
// Return a type with only the methods of T that return R.
type MethodsWithReturnType<T, R> = {
[P in keyof T]: T[P] extends () => infer RR ? (RR extends R ? P : never) : never
}[keyof T]
// Filter away all keys except methods that return void and
// return a new type with those methods returning booleans.
type VoidMethodsToBoolMethods<T> = { [P in MethodsWithReturnType<T, void>]: () => boolean }
// Our test input class:
class MyTest {
x = 123
one() {}
two() {}
three() {
return 123
}
}
// Extract void methods from MyTest and make them boolean methods.
type MyTestBools = VoidMethodsToBoolMethods<MyTest>
// Proof:
const x: MyTestBools = {
one: () => true,
two: () => false,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment