我創建了一個類,在該類中我想創建一個由自身物件組成的陣列。在普通的javascript中,如果實作如下
class Person{
constructor(name){
this.name=name;
}
setList(list){
let listItem=[];
for(const lt of list){
listItem.push(new this.constructor(lt));
}
return listItem;
}
}
在打字稿中
class Person{
name:string;
constructor(name){
this.name=name;
}
setList=(list:Array<string>)=>{
let listItem=[];
for(const lt of list){
listItem.push(new this.constructor(lt));
}
return listItem;
}
}
我收到上面的代碼錯誤this.constructor(lt)如下
This expression is not constructable.
Type 'Function' has no construct signatures.ts(2351)
uj5u.com熱心網友回復:
在 TypeScript 中,類this.constructor中的型別始終為Function; 但是,TypeScript 允許您在其宣告中對類進行參考,因此,只需將 替換為this.constructor類的名稱 ( Person),它本身就可以正常作業。見下文:
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
setList = (list: Array<string>) => {
let listItem = [];
for (const lt of list) {
listItem.push(new Person(lt));
}
return listItem;
};
}
如果您絕對需 this.constructor要這樣做,您可以像這樣強烈鍵入建構式:
class Person {
name: string;
["constructor"]: typeof Person;
constructor(name: string) {
this.name = name;
}
setList = (list: Array<string>) => {
let listItem = [];
for (const lt of list) {
listItem.push(new this.constructor(lt));
}
return listItem;
};
}
希望這可以幫助!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/441396.html
標籤:javascript 打字稿 班级 目的 ecmascript-6
上一篇:在python中替換物件的實體
