TypeScript错误:类型中缺少属性'0'

问题描述 投票:41回答:4

我有这样的界面

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

我无法控制更改界面,因为它已在其他地方使用。初始化此配置变量的正确方法是什么?

提前感谢。

javascript typescript knockout.js observable
4个回答
43
投票

我遇到了同样的问题,并通过将界面更改为:]解决了它。

    interface Details {
        Name: {
            First: string;
            Last: string;
        }[];
    }

我知道您可能不希望更改界面,但希望这对处于这种情况的任何人都有所帮助。


23
投票

此错误可能来自错误地键入数组(就像我刚才所做的那样:):

myArray:[]; //Incorrect, results in error message of `Property '0' is missing in type`

myArray: Array<string>; //Correct

myArray: string[]; //Also correct

14
投票

在此类型定义中:

interface Details {
  Name: [{
    First: string;
    Last: string;
  }];
}

10
投票

将界面更新为以下内容应该可以解决此问题:

 interface Details {
        Name: Array<{
            First: string;
            Last: string;
        }>;
    }
© www.soinside.com 2019 - 2024. All rights reserved.