我有很多带有静态变量的类,像这样:
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>
.所以,我的问题是:我怎样才能做到这一点?
最佳答案
您不能访问类型的属性,只能访问传入的参数,因为类型在运行时不存在。
但是您可以将类传递给构造函数,然后访问其属性。
例如
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);
关于typescript - 如何从泛型类访问静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45270946/