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

标签 typescript generics typescript-generics

我有很多带有静态变量的类,像这样:

user.ts:

export class User {
  static modelKey = 'user';

  // other variables
}

car.ts:

export class Car {
  static modelKey = 'car';

  // other variables
}

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

const dataSource = new DataSource<Car>();

数据源.ts:

export class DataSource<T> {

  constructor() {
    console.log(T.modelKey); // won't compile
  }  
}

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

Playground

最佳答案

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

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

例如

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);

Playground link

关于typescript - 如何从泛型类访问静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45270946/

相关文章:

typescript - 在泛型中使用泛型类类型

javascript - 如何在指令中使用 RegExp 并通过 Angular 8 进行验证

node.js - 从 Windows 命令行运行 tsc

linq - where 子句的通用表达式 - "The LINQ expression node type ' Invoke' 在 LINQ to Entities 中不受支持。”

c# - 是否可以让非泛型方法返回泛型类型?

java - 格式化数组元素

TypeScript 通用默认类型与上下文类型

typescript - TypeScript 条件类型的映射与受约束的泛型不同吗?

TypeScript discriminating union - 区分属性类型的参数

javascript - 如果没有 .js 扩展名,则为 ERR_MODULE_NOT_FOUND