Home > front end >  ES6 typescript class create object of itself inside
ES6 typescript class create object of itself inside

Time:03-10

I have created a class and inside that class i want to create an array that consist of object of itself. In normal javascript if achieve it as follow

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

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 expression is not constructable.
  Type 'Function' has no construct signatures.ts(2351)

CodePudding user response:

In TypeScript, the type of this.constructor in a class is always 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. 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:

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!

  • Related