Created
November 22, 2018 18:02
-
-
Save blixt/456867b9fafc3b480fd244341c13fea8 to your computer and use it in GitHub Desktop.
Did you know TypeScript's type system is Turing complete?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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