【问题标题】:Typescript error: A private property is missing?打字稿错误:缺少私有财产?
【发布时间】:2016-03-14 04:34:34
【问题描述】:

我有一个带有私有属性的类,但是当我尝试使用这些元素创建一个数组时,我收到以下错误:

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

我不明白为什么打字稿会抱怨甚至不在构造函数中的私有属性。

【问题讨论】:

    标签: typescript angular


    【解决方案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'] })
    ];
    

    【讨论】:

      猜你喜欢
      • 2018-02-19
      • 1970-01-01
      • 2011-02-15
      • 2017-12-22
      • 2021-09-23
      • 1970-01-01
      • 2016-11-17
      • 2023-03-17
      • 2013-11-27
      相关资源
      最近更新 更多