具有嵌套对象的对象数组的Typescript接口

时间:2020-03-13 04:39:36

标签: angular typescript dependency-injection

我有这样的对象数组:

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;字段:{...;};} | ... 7个以上... | {...;})[]'缺少类型'IExampleConfig'的以下属性:路径,pageTitle,字段

2 个答案:

答案 0 :(得分:1)

而不是这样写:

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

尝试一下:

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

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

答案 1 :(得分:0)

似乎您输入的类型错误。

执行此操作:

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]