簡體   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