Skip to content

Instantly share code, notes, and snippets.

@sgoguen
Created January 29, 2021 02:05
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 sgoguen/34d5b2bf677028c44e7aa9fc47cdbfc7 to your computer and use it in GitHub Desktop.
Save sgoguen/34d5b2bf677028c44e7aa9fc47cdbfc7 to your computer and use it in GitHub Desktop.
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