Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript create type from static values of class

I have a Market class which has only 1 parameter: name.

class Market {
  name: string

  constructor(name: string) {
    this.name = name
  }
}

I then have a Markets class which is a static collection of several markets.

class Markets {
  static M1 = new Market("M1M")
  static M2 = new Market("M2M")
  static M3 = new Market("M3M")
}

I was wondering if there was a way to extract all name parameters from all markets into a type, such that the type would look something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type MarketNames = "M1M" | "M2M" | "M3M"

I know about the keyof operator, is it the way?

Thanks.

>Solution :

For this to work, your class has to be generic, so we can "extract" the generic out of it later:

class Market<Name extends string> {
  name: Name;

  constructor(name: Name) {
    this.name = name
  }
}

Then we create our type to extract the names:

type NamesOfMarkets<T> = Extract<T[keyof T], Market<string>> extends Market<infer N> ? N : never;

We’re filtering out the values of the class for only Markets, then we infer the name and return that.

Note: you must pass the class as typeof Markets to get the constructor type. Markets by itself is simply a class instance.

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading