简体   繁体   English

ES6 typescript class 在里面创建自己的 object

[英]ES6 typescript class create object of itself inside

I have created a class and inside that class i want to create an array that consist of object of itself.我创建了一个 class 并且在该 class 中我想创建一个由 object 本身组成的数组。 In normal javascript if achieve it as follow在正常情况下 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;
     }
}

In typescript typescript

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;
     }
}

i get error above code this.constructor(lt) as follow我在代码this.constructor(lt)上面得到错误如下

This expression is not constructable.
  Type 'Function' has no construct signatures.ts(2351)

In TypeScript, the type of this.constructor in a class is always Function ;在TypeScript中,class中this.constructor的类型总是Function however, TypeScript allows you to make a reference to a class within its declaration, so, simply replacing the this.constructor with the name of the class, ( Person ), itself will work fine.但是,TypeScript 允许您在其声明中引用 class,因此,只需将this.constructor替换为 class 的名称 ( Person ),它本身就可以正常工作。 See below:见下文:

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;
  };
}

If you absolutely need to go the this.constructor way, you can strongly type the constructor like so:如果您绝对需要 go 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;
  };
}

Hope this helps!希望这可以帮助!

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

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