Created
January 29, 2021 02:05
-
-
Save sgoguen/34d5b2bf677028c44e7aa9fc47cdbfc7 to your computer and use it in GitHub Desktop.
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
class A { | |
keya = "a" as const; | |
} | |
class B { | |
keyb = "b" as const; | |
} | |
// Turned your class map into a constructor map to simplify it. | |
const classMap = { | |
'a': () => new A(), | |
'b': () => new B() | |
} | |
type ClassMap = typeof classMap; | |
const pickSomething = <K extends keyof ClassMap>(key: K) => { | |
// Simply looking up the function returns the appropriate function type | |
return classMap[key]; | |
} | |
const a = pickSomething('a')().keya; | |
const b = pickSomething('b')().keyb; | |
const pickSomething2 = <K extends keyof ClassMap>(key: K) => { | |
// Why does calling the function change things? | |
const f = classMap[key]; | |
type R = ReturnType<typeof f>; | |
const r: R = f(); | |
return r; | |
} | |
const a1 = pickSomething2('a').keya; | |
const b1 = pickSomething2('b').keyb; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment