我的界面是这样的
export interface Details {
Name: [{
First: string;
Last: string;
}];
} 我有一个可观察的配置变量:
Configuration: KnockoutObservable<Details> = ko.observable<Details>();
我想在构造函数中为它赋值,如下所示:
config = {
Name: [{
First: "ABC",
Last: "DEF"
},
{
First: "LMN",
Last: "XYZ"
}]
};
this.Configuration(config);我得到了一个错误:
Types of property 'Name' is incompatible and property '0' is missing in type.
Type '{ First:string; Last:string; }[]' is not assignable to
type '[{ First: string; Last:string; }]'我无法控制界面的更改,因为它正被其他地方使用。
初始化此配置变量的正确方法是什么?
提前谢谢。
发布于 2017-09-26 15:51:21
我遇到了同样的问题,并通过将界面更改为:
interface Details {
Name: {
First: string;
Last: string;
}[];
}我知道你可能不想改变界面,但希望这对处于这种情况下的任何人都有帮助。
发布于 2019-03-22 09:44:35
此错误可能来自于错误地键入数组(就像我刚才所做的那样):
myArray:[]; //Incorrect, results in error message of `Property '0' is missing in type`
myArray: Array<string>; //Correct
myArray: string[]; //Also correct原因是方括号表示Typescript中的元组,而不是数组。
发布于 2017-06-09 13:29:59
在此类型定义中:
interface Details {
Name: [{
First: string;
Last: string;
}];
}Name在编译时不是数组。它是一个只有一个元素的元组。Typescript中的元组可以有额外的元素,但它们不能缺少元素。作为一个1元组,Name本质上是一个必须至少有一个元素的数组。
但是,在该值中:
const config = {
Name: [{
First: "ABC",
Last: "DEF"
},
{
First: "LMN",
Last: "XYZ"
}]
};由于没有显式类型,因此此处的Name属性默认为数组类型。数组可以有任意数量的元素,包括零--这不适合1元组。这就是你的错误。
你的错误可以通过给编译器一个提示,你的文字实际上是一个元组来修复:
const config: Details = { Name: [{...}, {...}] };如果您确实需要能够接受一组名称,则必须进行一些强制转换,可能如下所示:
if (names.length > 0) {
const config = {
Name: names as Details['Name']
};
Configuration(config);
}(如果可以确定元组只是编写类型的人的一个错误,则可以删除if检查。)
元组引用:https://www.typescriptlang.org/docs/handbook/basic-types.html
https://stackoverflow.com/questions/44447730
复制相似问题