【问题标题】:Typescript interface for Array of object that has nested object具有嵌套对象的对象数组的 Typescript 接口
【发布时间】:2020-03-13 04:39:36
【问题描述】:

我有这样的对象数组:

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

它给了我错误:Type '({ path: string; pageTitle: string; fields: { fullName: string; mobilePhoneNumber: string; emailAddress: string; emailIsOwn: string; mediasource: string; }; } | { path: string; pageTitle: string; fields: { ...; }; } | ... 7 more ... | { ...; })[]' 缺少类型“IExampleConfig”的以下属性:路径、页面标题、字段

【问题讨论】:

  • EXAMPLE_CONFIG: IExampleConfig-> EXAMPLE_CONFIG: IExampleConfig[] 指定an array

标签: angular typescript dependency-injection


【解决方案1】:

而不是这样写:

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

试试这个:

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

? 是一个 Typescript 符号,表示接口属性是可选的

【讨论】:

    【解决方案2】:

    好像你的类型不对。

    这样做:

    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]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      • 2021-07-04
      • 2019-10-28
      • 2016-06-02
      相关资源
      最近更新 更多