簡體   English   中英

TypeScript:類型“ Function”上不存在屬性“ propertyName”

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

盡管在https://www.typescriptlang.org/play/上生成的JavaScript按預期工作,但TypeScript編譯器在以下代碼示例中給我一個錯誤

錯誤是: 錯誤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"

我有什么辦法可以解決此錯誤?

取代這個

this.constructor.tableName()

有了這個

ActiveRecord.tableName()

由於必須使用類名稱空間來調用靜態函數。

要修復TypeScript錯誤並仍然獲得預期的行為(不使用ActiveRecord.tableName()),可以將構造函數強制轉換為ActiveRecord的類型

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

參考鏈接: 通過打字稿中的this.constructor訪問靜態屬性

一種方法是不在屬性上使用static關鍵字。 否則使用ActiveRecord.tableName()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM