简体   繁体   English

Typescript 从 class 的 static 值创建类型

[英]Typescript create type from static values of class

I have a Market class which has only 1 parameter: name.我有一个市场class ,它只有 1 个参数:名称。

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 ,它是几个市场的static集合。

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?我知道keyof运算符,是这样吗?

Thanks.谢谢。

For this to work, your class has to be generic, so we can "extract" the generic out of it later:为此,您的 class 必须是通用的,因此我们稍后可以从中“提取”通用的:

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.我们过滤掉 class 的值,仅用于市场,然后我们推断名称并返回它。

Note: you must pass the class as typeof Markets to get the constructor type.注意:您必须将 class 作为typeof Markets传递才能获取构造函数类型。 Markets by itself is simply a class instance. Markets本身就是一个 class 实例。

Playground操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM