当前,尝试在Typescript中创建新对象时出现奇怪的行为。有两类:
export class SkaterDrawn {
private ID;
private name;
...
constructor(input?:any) {
this.ID = input.ID;
...
}
export class SkaterDrawnTeam extends SkaterDrawn {
private skaters:SkaterDrawn[];
constructor(skaters:SkaterDrawn[]) {
super(skaters[0]);
this.skaters = skaters;
}
...
}
this.registeredSkaters
包含类型为SkaterDrawn
的元素数组。现在,我将该数组分组为一个大块数组,如下所示:
this.registeredSkaters = this.registeredSkaters.groupBy('teamID');
this.registeredSkaters = Object.values(this.registeredSkaters);
这将输出:
[
[SkaterDrawn,SkaterDrawn,SkaterDrawn],
[SkaterDrawn,SkaterDrawn,SkaterDrawn],
[SkaterDrawn,SkaterDrawn,SkaterDrawn]
]
现在我正尝试以此创建一个新对象:
let teams = this.registeredSkaters.map((item:SkaterDrawn[]) =>
new SkaterDrawnTeam(item);
})
我期望得到一个SkaterDrawnTeam
的数组,但是编译失败并显示
ERROR in src/app/competition/components/drawing/drawing.component.ts(166,30):
error TS2345: Argument of type 'SkaterDrawn' is not assignable to parameter of type 'SkaterDrawn[]'.
Type 'SkaterDrawn' is missing the following properties from type 'SkaterDrawn[]': length, pop, push, concat, and 35 more.
Line 166,30
是我尝试做的行new SkaterDrawnTeam(item)
,我不知道为什么会失败。我在做什么错了,我该如何解决?
非常感谢您的帮助。
答案 0 :(得分:1)
问题在于SkaterDrawn []与(typeof SkaterDrawn)[]
不同let teams = this.registeredSkaters.map((item: (typeof SkaterDrawn)[]) => {
return new SkaterDrawnTeam(item);
});
然后将您的班级更改为
export class SkaterDrawnTeam extends SkaterDrawn {
private skaters:(typeof SkaterDrawn)[];
constructor(skaters:(typeof SkaterDrawn)[]) {
super(skaters);
this.skaters = skaters;
}
}