繁体   English   中英

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

[英]TypeScript Error: Property '0' is missing in type

我的界面是这样的

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

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

提前致谢。

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

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

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

这个错误可能来自错误地输入数组(就像我刚刚做的那样):

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

myArray: Array<string>; //Correct

myArray: string[]; //Also correct

原因是括号表示 Typescript 中的元组,而不是数组。

文档

在这个类型定义中:

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

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

 interface Details {
        Name: Array<{
            First: string;
            Last: string;
        }>;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM