如何将数组转换为具有索引签名和类作为类型的对象?



我有A型、B型和一个叫做Person的类。我需要将A类型的数组转换为B类型的数组然后以某种方式将它作为输入数据发送给类。我真的卡住了,不知道该怎么做。

类型A和此类型的数组:

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']];

B型:

type B = {
[id: string]: 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.`
);
}}

我这样做了:

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

但是由于某些原因,现在我不能像这样调用类的方法:

for (let person of b) {
console.log(person.tellUsAboutYourself());
}

考虑这个例子:

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)
}))

游乐场

您只需要在Person构造函数参数中保留Params元素的顺序。

相关内容

  • 没有找到相关文章

最新更新