TmTron
TmTron

Reputation: 19381

How to get a union type of classes in an object

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

Answers (1)

ferikeem
ferikeem

Reputation: 537

Edit:

I found the type we were looking for: InstanceType.

type XValues = InstanceType<typeof X[keyof typeof X]>;

Playground link

Upvotes: 1

Related Questions