如何从泛型类访问静态变量?

dev*_*054 5 generics typescript typescript-generics

我有很多带有静态变量的类,如下所示:

用户.ts:

export class User {
  static modelKey = 'user';

  // other variables
}
Run Code Online (Sandbox Code Playgroud)

汽车.ts:

export class Car {
  static modelKey = 'car';

  // other variables
}
Run Code Online (Sandbox Code Playgroud)

在某个地方,我只想像这样调用DataSource(见下文):

const dataSource = new DataSource<Car>();
Run Code Online (Sandbox Code Playgroud)

数据源.ts:

export class DataSource<T> {

  constructor() {
    console.log(T.modelKey); // won't compile
  }  
}
Run Code Online (Sandbox Code Playgroud)

当然,它不会编译,因为我不能简单地使用T.<variable>. 所以,我的问题是:我怎样才能做到这一点?

操场

Gre*_*egL 2

您无法访问类型的属性,只能访问传入的参数的属性,因为类型在运行时不存在。

但是您可以将类传递给构造函数,然后访问该类的属性。

例如

export class User {
  static modelKey = 'user';

  // other variables
}
export class Car {
  static modelKey = 'car';

  // other variables
}

interface ModelClass<T> {
  new (): T;
  modelKey: string;
}

export class DataSource<T> {

  constructor(clazz: ModelClass<T>) {
    console.log('Model key: ', clazz.modelKey); // will compile
  }  
}

new DataSource(Car);
Run Code Online (Sandbox Code Playgroud)

游乐场链接