2016-03-13 58 views
2

我有一個私人性質的一類,但是當我嘗試創建這個元素,我得到以下錯誤的數組:手稿錯誤:私人財產丟​​失?

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

Array類:

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

我不明白爲什麼打字稿抱怨私人財產,即使不在構造函數中。

回答

1

你的方式,你正在創建一個類型爲對象[]的數組。你需要做的是調用像下面的構造函數告訴你正在創建一個轉譯器培訓對象:

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