Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
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. 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)
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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!

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda