簡體   English   中英

具有嵌套對象的對象數組的打字稿接口

[英]Typescript interface for Array of object that has nested object

我有這樣的對象數組:

export const EXAMPLE_CONFIG: IExampleConfig = [
 {
  urlPath: '/test/test',
  page: 'test',
  fields: {
   fullName: 'a',
   mobilePhoneNumber: 'b',
   emailAddress: 'c',
   .......
  }
 },
 {
  ... same as above
 },
]

我創建了一個這樣的界面:

export interface IExampleConfig {
  path: string;
  pageTitle: string;
  fields: { [key: string]: string };
}

它給了我錯誤:類型 '({ path: string; pageTitle: string; fields: { fullName: string; mobilePhoneNumber: string; emailAddress: string; emailIsOwn: string; mediasource: string; }; } | { path: string; pageTitle : string; fields: { ...; }; } | ... 7 more ... | { ...; })[]' 缺少類型 'IExampleConfig' 中的以下屬性:path、pageTitle、fields

而不是寫這個:

export interface IExampleConfig {
  path: string;
  pageTitle: string;
  fields: { [key: string]: string };
}

嘗試這個:

export interface IExampleConfig {
  path?: string;
  pageTitle?: string;
  fields?: { [key: string]?: string };
}

? 是一個打字稿符號,它標志着接口屬性是可選的

好像你的類型不對。

做這個:

export const EXAMPLE_CONFIG: IExampleConfig[]

而不是這個:

export const EXAMPLE_CONFIG: IExampleConfig

另外,如果您想讓界面可選,而不是將整個界面變為可選,您可以使用 Typescript 實用程序類型 - Partial。 它接收接口並根據使用情況將其轉換為可選接口。

宣言:

export interface IExampleConfig {
  path: string;
  pageTitle: string;
  fields: { [key: string]: string };
}

用法

let example: Partial<IExampleConfig> = { path: 'path/to/file' }

您可以在此處閱讀更多相關信息:[ https://www.typescriptlang.org/docs/handbook/utility-types.html#partialt][1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM