Home > other >  Typescript create type from static values of class
Typescript create type from static values of class

Time:09-29

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:

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

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

Thanks.

CodePudding user response:

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

  • Related