我有一个私有属性的类但是当我尝试使用这些元素创建一个数组时,我收到以下错误:
error TS2322: Type '{ "id": number; "totalTime": number; "team": { "id": number; "name": string; }; }[]' is not assignable to type 'Training[]'.
[0] Type '{ "id": number; "totalTime": number; "team": { "id": number; "name": string; }; }' is not assignable to type 'Training'.
[0] Property 'remainingTime' is missing in type '{ "id": number; "totalTime": number; "team": { "id": number; "name": string; }; }'
数组类:
import { TEAMS } from './mock-teams';
import { Training } from './training';
export var TRAININGS: Training[] = [
{"id": 0, "totalTime": 60, "team": {"id": TEAMS[0]['id'], "name": TEAMS[0]['name'] } },
{"id": 1, "totalTime": 60, "team": {"id": TEAMS[0]['id'], "name": TEAMS[0]['name'] } }
];
培训课程:
export class Training {
private remainingTime: number = 0;
constructor(
public id: number,
public totalTime: number,
public team?: Team) {
}
}
我不明白为什么打字稿会抱怨一个甚至不在构造函数中的私有财产。
答案 0 :(得分:1)
您采用的方式是创建一个类型 Object [] 的数组。您需要做的是调用下面的构造函数来告诉您正在创建 Training 对象的转换器:
import { TEAMS } from './mock-teams';
import { Training } from './training';
export var TRAININGS: Training[] = [
new Training(0,60, {"id": TEAMS[0]['id'], "name": TEAMS[0]['name'] }),
new Training(1,60, {"id": TEAMS[0]['id'], "name": TEAMS[0]['name'] })
];