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

166
Visualizações
How do I transform array into an object with index signature and class as a type?

I have type A, type B and a class called Person. I need to transform array of type A into array of types B and then somehow send it to the class as an input data. I am really stuck and not sure how I do all of this.

Type A and array of this type:

type A = Array<[string, number, string]>;
const a: A = [
['Name1', 15, 'City1'],
['Name2', 44, 'City2'],
['Name3', 23, 'City3'],
['Name4', 73, 'City4'],
['Name5', 12, 'City5']
['Name6', 37, 'City6']];

Type B:

type B = {
[id: string]: Person}

Class Person:

class Person {
_id: string; // must be unique
age: number;
name: string;
city: string;

constructor(data) {
    if (data == null) {
        console.log("No data presented")
    } else {
        this._id = data._id
        this.age = data.age
        this.name = data.name
        this.city = data.city
    }
}

tellUsAboutYourself() {
    console.log(
        `Person with unique id = ${this._id} says:\n
         Hello! My name is ${this.name}. I was born in ${this.city}, ${this.age} years ago.`
    );
}}

I did this:

export const b: B[] = a.map(([name,age,city], index) => ({
[index]: new Person(${index}, {name, age, city})}))

But now I can't call method of class like this for some reason:

for (let person of b) {
         console.log(person.tellUsAboutYourself());
     }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Consider this example:

type Params = [name: string, age: number, city: string]

type A = Array<Params>;

type B = {
  [id: string]: Person
}

class Person {
  constructor(
    public _id: string,
    public name: string,
    public age: number,
    public city: string
  ) { }

}

const a: A = [
  ['Name1', 15, 'City1'],
  ['Name2', 44, 'City2'],
  ['Name3', 23, 'City3'],
  ['Name4', 73, 'City4'],
  ['Name5', 12, 'City5'],
  ['Name6', 37, 'City6']
];



export const b: B[] = a.map((elem, index) => ({
  [index]: new Person(`${index}`, ...elem)
}))

Playground

You just need to preserve order of Params elems in Person constructor arguments.

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