首页 > 解决方案 > 如何为包含键/值对以及嵌套对象的对象/数组定义接口?

问题描述

我正在输入一个本地化库,并且我的目标是对其进行强类型化(因为它将在多个角度应用程序中重复使用)并且 - 同时 - 向后兼容,因此我们不会有重写所有现有的本地化文件。

但是,所述本地化文件的结构让我有点头疼。每个例子:

{
  'any-random-key': 'This is a string',
  'another-random-key': {
    'random-key': 'This is a string'
  },
  'yet-another-random-key': {
    'random-key-2': 'This is a string',
    'random-key-3': {
      'random-key-4': 'This is a string',
      'random-key-5': {
        'random-key-6': 'This is a string'
      }
    }
  },
  'and-yet-another-random-key': {
    'random-key-6': {
      'random-key-7': {
        'random-key-8': 'This is a string'
      },
      'random-key-9': 'This is a string'
    }
  }
}

现在 - 我想我可以说服务接受translations: anytranslations: object- 但这对我来说有点太随意了(不是双关语)。

所以我尝试使用两个不同的接口:

export interface ITranslation {
  [s: string]: string;
}

export interface ITranslations {
  [s: string]: ITranslation;
}

然而,这没有any-random-key说:Type 'string' is not assignable to type 'ITranslation'

所以我调整我的ITranslations-interface 使它变成

export interface ITranslations {
  [s: string]: ITranslation | string;
}

修复了上述错误,但在'and-yet-another-random-key'说上引入了一个新错误Property ''and-yet-another-random-key'' is incompatible with index signature.

在这一点上,我有点难过。我想要实现的目标(遗留结构的强类型)根本不合理吗?

标签: typescriptinterface

解决方案


对于任何任意级别的嵌套(换句话说,您的数据对象可以是任意级别的深度),您可以简单地自引用接口,如下所示:

/** @interface */
export interface ITranslations {
  [s: string]: ITranslations | string;
}

请参阅上面 TypeScript 操场上的示例


如果您只想允许 3 级深度嵌套,那么界面将不得不是冗长的:TypeScript 不允许您定义“深度”(即嵌套的程度):

/** @interface */
export interface ITranslations<T = string> {
  [s: string]: T | string;
}

/** @type */
export type ITranslationsMax3Levels = ITranslations<ITranslations<ITranslations<ITranslations>>>;

const data: ITranslationsMax3Levels = { ... }

请参阅上面 TypeScript 操场上的示例


推荐阅读