简体   繁体   English

TypeScript:类型“ Function”上不存在属性“ propertyName”

[英]TypeScript: Property 'propertyName' does not exist on type 'Function'

TypeScript compiler is giving me an error on the following code example although the generated JavaScript on https://www.typescriptlang.org/play/ works as intended 尽管在https://www.typescriptlang.org/play/上生成的JavaScript按预期工作,但TypeScript编译器在以下代码示例中给我一个错误

The error is: error TS2339: Property 'tableName' does not exist on type 'Function'. 错误是: 错误TS2339:类型'Function'上不存在属性'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"

Is there is anything I can do to fix this error? 我有什么办法可以解决此错误?

Replace this 取代这个

this.constructor.tableName()

With this 有了这个

ActiveRecord.tableName()

As a static function is must be called using the class namespace. 由于必须使用类名称空间来调用静态函数。

To fix the TypeScript error and still get the intended behavior (not using ActiveRecord.tableName()) you can cast the constructor to a typeof ActiveRecord 要修复TypeScript错误并仍然获得预期的行为(不使用ActiveRecord.tableName()),可以将构造函数强制转换为ActiveRecord的类型

(this.constructor as typeof ActiveRecord).tableName())

Reference link: Access to static properties via this.constructor in typescript 参考链接: 通过打字稿中的this.constructor访问静态属性

One way would be to NOT use the static keyword on your properties. 一种方法是不在属性上使用static关键字。 Otherwise use ActiveRecord.tableName() 否则使用ActiveRecord.tableName()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM