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

288
Visualizações
Typescript - how to pass MyClass.new as method reference?

I have an array of objects, where each object looks like this:

{ id: 'string', name: 'string' }

Given this class:

class User {
  constructor(obj: Record<string, string>) {
    Object.assign(this, obj);
  }

  id: string; 
  name: string;
}

I want to use Array.map() to create an array of User:

const users = userObjects.map(o => new User(o));

The above works, but feels wrong: is there a way to pass a reference to the User's new and avoid the arrow function?

I'm not really sure if the answer is different between Javascript and Typescript (I suspect it isn't), but FWIW I'm coding in Typescript.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

No, there isn't (other than a utility function you might write to do that arrow function for you, but that's just an abstraction on what you already have). The issue is that there is no new method (like Java's User::new), there is only the User function itself, and whether it creates a User instance or throws an error (in modern environments) depends on how you call it. If you call it via new (or a similar mechanism like Reflect.construct), it creates a User instance. If you call it directly, it throws an error (in ES2015+; if you're compiling down to ES5, it won't, but it won't work properly either).

What you have (the wrapper arrow function) is a perfectly good way to do it (and probably what I'd do).

If you need to do this in several places, you could put a static method on User:

class User {
    // ...
    static create(...args) {
        return new User(...args);
    }
}
// ...
const users = userObjects.map(User.create);

(Note that create won't work properly in User subclasses [depending on your definition of "properly"], it always creates a User instance, even if called as UserSubclass.create(/*...*/). Normally you could use this instead of User [new this(...args)], which while it looks odd works provided the call sets this correctly [as User.create(/*...*/) or UserSubclass.create(/*...*/) would], but map won't set this correctly so that wouldn't work unless you bind create or remember to pass the second argument to map [.map(User.create, User)], which takes us back to: a wrapper arrow function probably makes more sense.)

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