Typescript 如何从泛型类访问静态变量?
我有许多带有静态变量的类,如下所示:Typescript 如何从泛型类访问静态变量?,typescript,generics,typescript-generics,Typescript,Generics,Typescript Generics,我有许多带有静态变量的类,如下所示: const dataSource = new DataSource<Car>(); user.ts: export class User { static modelKey = 'user'; // other variables } export class Car { static modelKey = 'car'; // other variables } export class DataSource<T&
const dataSource = new DataSource<Car>();
user.ts:
export class User {
static modelKey = 'user';
// other variables
}
export class Car {
static modelKey = 'car';
// other variables
}
export class DataSource<T> {
constructor() {
console.log(T.modelKey); // won't compile
}
}
car.ts:
export class User {
static modelKey = 'user';
// other variables
}
export class Car {
static modelKey = 'car';
// other variables
}
export class DataSource<T> {
constructor() {
console.log(T.modelKey); // won't compile
}
}
在某个地方,我只想像这样调用数据源
(见下文):
const dataSource = new DataSource<Car>();
constdatasource=newdatasource();
数据源。ts:
export class User {
static modelKey = 'user';
// other variables
}
export class Car {
static modelKey = 'car';
// other variables
}
export class DataSource<T> {
constructor() {
console.log(T.modelKey); // won't compile
}
}
导出类数据源{
构造函数(){
console.log(T.modelKey);//无法编译
}
}
当然,它不会编译,因为我不能简单地使用t.
。所以,我的问题是:我如何才能做到这一点
您不能访问类型的属性,只能访问传入的参数,因为类型在运行时不存在 但您可以将类传递给构造函数,然后访问该类的属性 e、 g
导出类用户{
静态modelKey='user';
//其他变量
}
出口级轿车{
静态模型键='car';
//其他变量
}
接口模型类{
新的():T;
modelKey:字符串;
}
导出类数据源{
构造函数(clazz:ModelClass){
console.log('Model key:',clazz.modelKey);//将编译
}
}
新数据源(Car);
我对typescript了解不多,但看起来您正试图从t访问一个变量,t中没有变量modelKey的定义。最好是在构造函数中请求一个抽象变量,它是Car和User的父变量,并使用它来代替T。@Elijahsedarita,你能详细说明一下吗?介意复制一下吗?谢谢,退房。编辑:不要相信我看GregL的回答谢谢,虽然它可能在操场上正常工作,但我在我的项目中得到了以下错误:
'type'type of car'的参数不能归因于类型'ModelClass'的参数。
当我尝试执行新数据源(car)代码>。我怀疑这是因为TS 2.4.x引入了更好的泛型检查。在我的项目中,我使用的是最新版本的TS(2.4.2),游乐场使用的是2.3.3(我想)。您能帮助我吗?类型为“typeof Car”的完整错误[ts]参数不能分配给类型为“ModelClass”的参数。类型“Car”不可分配给类型“T”。
我设法将其从ModelClass
中排除泛型:interface ModelClass{…}
并完全删除new()
。这是正确的方法吗?@dev_054:问题可能是您的项目的Car
类没有无参数构造函数。要使@GregL的代码与任何类一起工作,您应该将new():T
更改为new(…args:any[]):T
。此外,请记住,如果您想在DataSource
方法中使用T
的静态属性,如clazz.modelKey
,而不是构造函数,您应该将clazz
存储为实例属性;最简单的方法是将clazz
参数声明为public
(即构造函数(public clazz:ModelClass)
)。