Skip to content

Instantly share code, notes, and snippets.

@AngusFu
Created April 13, 2021 09:17
Show Gist options
  • Save AngusFu/7412dabf0e35d5e7caf796df4383b82d to your computer and use it in GitHub Desktop.
Save AngusFu/7412dabf0e35d5e7caf796df4383b82d to your computer and use it in GitHub Desktop.
class A {
x = 1;
}
class B {
y = 2;
}
class C {
z = 3;
}
const Comps = {
A,
B,
C,
} as const;
function instantiate<K extends keyof typeof Comps>(type: K) {
const Ctor = Comps[type];
return new Ctor() as typeof Ctor extends { new (): infer U } ? U : never;
}
const a = instantiate('A');
console.log(a.x);
const b = instantiate('B');
console.log(b.y);
const c = instantiate('C');
console.log(c.z);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment