【问题标题】:TypeScript: Property 'propertyName' does not exist on type 'Function'TypeScript:“函数”类型上不存在属性“propertyName”
【发布时间】:2016-12-19 10:50:17
【问题描述】:

TypeScript 编译器在以下代码示例中给我一个错误,尽管 https://www.typescriptlang.org/play/ 上生成的 JavaScript 按预期工作

错误是:error TS2339: Property 'tableName' does not exist on type 'Function'.

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"

有什么办法可以解决这个错误吗?

【问题讨论】:

  • 使用 ActiveRecord.tableName() 不会调用子类的重写方法,这会破坏@Joe 的预期行为

标签: javascript typescript


【解决方案1】:

要修复 TypeScript 错误并仍然获得预期的行为(不使用 ActiveRecord.tableName()),您可以将构造函数强制转换为 typeof ActiveRecord

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

参考链接:Access to static properties via this.constructor in typescript

【讨论】:

    【解决方案2】:

    替换这个

    this.constructor.tableName()
    

    有了这个

    ActiveRecord.tableName()
    

    作为静态函数,必须使用类命名空间调用。

    【讨论】:

      【解决方案3】:

      一种方法是不在您的属性上使用 static 关键字。否则使用 ActiveRecord.tableName()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-02
        • 2018-08-17
        • 1970-01-01
        • 2023-02-06
        • 2019-06-28
        • 1970-01-01
        • 1970-01-01
        • 2020-08-02
        相关资源
        最近更新 更多