Home > OS >  Get typeof type from type with classes
Get typeof type from type with classes

Time:01-27

Currently I have 2 types like this:

export type Component = AComponent| BComponent| CComponent;
export type ComponentType= typeof AComponent| typeof BComponent| typeof CComponent;

Instead of duplicating code like this, is there a way to write my components once, and get two types similar to this?

Thank you

CodePudding user response:

You can use InstanceType on the ComponentType union (Assuming *Component are classes). InstanceType is distributive, so you will get the same union as Component

export type ComponentType= typeof AComponent| typeof BComponent| typeof CComponent;
export type Component =InstanceType<ComponentType> // AComponent | BComponent | CComponent

Playground Link

  •  Tags:  
  • Related