Reputation: 19381
I have a constant object like this:
class A {}
class B {}
const X = {
a: A,
b: B
} as const
How can I get a union type of the object values A | B
(without duplicating code)?
e.g. I want to achieve this:
// I need
type XUnion = A | B;
// so that this works
const bar: XUnion = new A();
I have tried to do this, but it does not work:
type XValues = typeof X[keyof typeof X];
// now XValues = typeof A | typeof B
const foo: XValues = new A();
// ^^^ compile error:
// Type 'A' is not assignable to type 'XValues'.
// Property 'prototype' is missing in type 'A' but required in type 'typeof B'.
Here is a link to the example in the typescript playground
Upvotes: 0
Views: 1082
Reputation: 537
Edit:
I found the type we were looking for: InstanceType.
type XValues = InstanceType<typeof X[keyof typeof X]>;
Upvotes: 1