Alexander Zeitler
Alexander Zeitler

Reputation: 13109

Get names of classes as union type of string

I have several classes like

class A {}
class B {}
class N {}

Is it possible to generate a union type from the class names like

type Classes = "A" | "B" | "N"

Upvotes: 0

Views: 784

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075279

You can create a union type from the classes like this:

type Classes = A | B | C;

Note there are no quotes. We're not dealing with string literals, we're dealing with type names.

No, you can't do it with string literals unless the classes are in an an object type where you can use the literals to refer to the interface's properties. For instance, this would work:

class A {}
class B {}
class C {}
interface All {
    A: A,
    B: B,
    C: C,
}
type Classes = All[keyof All];

But that's round-about, if you already have access to the type names of the classes directly.

Note that A, B, etc. refer to the type of instances of the classes. I couldn't tell for sure whether you wanted that or the type of the class functions themselves. If the latter, you add typeof in front or A, B, and C:

type Classes = typeof A | typeof B | typeof C;

or

class A {}
class B {}
class C {}
interface All {
    A: typeof A,
    B: typeof B,
    C: typeof C,
}
type Classes = All[keyof All];

Upvotes: 2

Related Questions