2016-08-12 69 views
1

打字稿編譯器存在是給我在下面的代碼示例雖然生成的JavaScript錯誤的https://www.typescriptlang.org/play/作品如預期打字稿:房產「propertyName的」不上鍵入「功能」

的錯誤是:錯誤TS2339 :屬性'tableName'在類型'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" 

有什麼我可以做些什麼來解決這個問題?

+0

使用ActiveRecord.tableName()將不會調用子類的重寫方法,這將打破預期的行爲@Joe –

回答

2

替換此

this.constructor.tableName() 

有了這個

ActiveRecord.tableName() 

爲靜態函數必須使用類的命名空間中調用。

0

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