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());
}
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)
}))
You just need to preserve order of Params
elems in Person
constructor arguments.