I successfully transformed an array of type A into an object with instances of the Person class. However, I'm facing an issue where I can't invoke methods of the Person class using the transformed array. Despite all console.log checks showing that everything was transformed correctly and b contains instances of the Person class rather than just arrays with data.
Below is the code snippet:
import crypto from "crypto"
type A = Array<[string, number, string]>;
type B = {
[id: string]: Person
}
export class Person {
_id: string; // must be unique
age: number;
name: string;
city: string;
constructor(name: string, age: number, city: string) {
this._id = Person.generateUniqueID(12);
this.age = age
this.name = name
this.city = city
}
private static generateUniqueID(len: number): string {
return crypto.randomBytes(Math.ceil(len/2))
.toString('hex')
.slice(0, len);
}
public tellUsAboutYourself(): string {
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.`
);
return `Person with unique id = ${this._id} says:\n Hello! My name is ${this.name}. I was born in ${this.city}, ${this.age} years ago.`
}
}
export const a: A = [
['name1', 24, 'city1'],
['name2', 33, 'city2'],
['name3', 61, 'city3'],
['name4', 60, 'city4']
];
export const b: B = a.reduce(function (value: any, [name, age, city]) {
let persona = new Person(name, age, city);
value[persona._id] = [persona.name, persona.age, persona.city]
return value;
}, {});
a successfully transforms to b, console log for b looks like this:
{
'd85750baf38f': [ 'name1', 24, 'city1' ],
'1f8fc00c6762': [ 'name2', 33, 'city2' ],
'8bac45ed719b': [ 'name3', 61, 'city3' ],
'1f00fa9086a2': [ 'name4', 60, 'city4' ]
}
console log for Object.keys(b) is:
[ 'd85750baf38f', '1f8fc00c6762', '8bac45ed719b', '1f00fa9086a2' ]
so how come when I do:
Object.keys(b).forEach(key => {
b[key].tellUsAboutYourself();
})
in tsc compiler it says:
exports.b[key].tellUsAboutYourself();
^
TypeError: exports.b[key].tellUsAboutYourself is not a function