gpt4 book ai didi

typescript 错误 : A private property is missing?

转载 作者:太空狗 更新时间:2023-10-29 19:31:19 27 4
gpt4 key购买 nike

我有一个带有私有(private)属性的类,但是当我尝试用这些元素创建一个数组时,出现以下错误:

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 会提示一个甚至不在构造函数中的私有(private)属性。

最佳答案

按照您的方式,您正在创建类型为 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'] })
];

关于 typescript 错误 : A private property is missing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35975405/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com