Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.