Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

168
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda