首页 > 解决方案 > 其属性仅在 TypeScript 中属于 A 和 B 类型的接口?

问题描述

我为我的配置创建了一个持有者,类型ButtonConfigs如下(如this answer中所建议)。

export interface ButtonConfigs {
  [key: string]: ButtonConfig;
}

我继续使用其他组件的配置,以便每种类型在组件中都有自己的配置属性。

...
buttonConfigs: ButtonConfigs = {};
folderConfigs: FolderConfigs = {};
txtBoxConfigs: TxtBoxConfigs = {};
...

然后我突然想到我应该能够将所有配置聚合到一个公共属性中。在我的情况下,这也很有意义。

但是,我不确定是否可以以允许不同类型的方式更改接口,但仍然限制configsnot to的内容any。我目前的方法设计不佳。

export interface Configs {
  [key: string]: any;
}

我如何告诉 TypeScript 该字段的类型应该是TextBoxConfigButtonConfig或者FolderConfig没有别的?

标签: angulartypescripttypescomplex-data-types

解决方案


您是否尝试过使用联合类型

interface ButtonConfig {
  a: string;
}
interface FolderConfigs {
  b: number;
}
interface TxtBoxConfigs {
  c: boolean;
}

export interface Configs {
  [key: string]: ButtonConfig | FolderConfigs | TxtBoxConfigs;
}

const config: Configs = {
  buttonConfig: {
    a: "testing"
  },
  folderConfig: {
    b: 1 
  },
  textConfig: {
    c: true 
  },
  anotherConfig: { // error: Type 'number' is not assignable to type 'string'.
    a: 1
  },
  moreConfig: {
    d: "test" // error: Object literal may only specify known properties, and 'd' does not exist in type 'ButtonConfig | FolderConfigs | TxtBoxConfigs'.
  }
}

这是操场示例


推荐阅读