TypeScript编译器在以下代码示例中给出了错误,尽管https://www.typescriptlang.org/play/上生成的JavaScript按预期工作
错误是: 错误TS2339:“函数”类型中不存在属性“tableName”。
class ActiveRecord {
static tableName(): string { // override this
return "active_record";
}
static findOne(): any {
return 'Finding a record on table: ' + this.tableName();
}
save(): void {
console.log('Saving record to table: ' + this.constructor.tableName());
}
}
class MyModel extends ActiveRecord {
static tableName(): string {
return "my_model";
}
}
let x = new MyModel();
x.save(); // "Saving record on table: my_model"
console.log(MyModel.findOne()); // "Finding a record on table: my_model"
我有什么办法可以解决这个错误吗?
答案 0 :(得分:2)
替换此
this.constructor.tableName()
有了这个
ActiveRecord.tableName()
因为必须使用类名称空间调用静态函数。
答案 1 :(得分:1)
要修复TypeScript错误并仍然获得预期的行为(不使用ActiveRecord.tableName()),您可以将构造函数强制转换为ActiveRecord类型
(this.constructor as typeof ActiveRecord).tableName())
参考链接:Access to static properties via this.constructor in typescript
答案 2 :(得分:0)
一种方法是不在属性上使用static关键字。否则使用ActiveRecord.tableName()