我想创建一个Reaction功能组件,它将预定义的组件之一作为props ,哪个逻辑取决于传入的组件.

因此,以下是可能的名称:

enum ComponentName {
  ComponentA: "component.a",
  ComponentB: "component.b",
  ComponentC: "component.c",
  // etc
}

现在最难的是,我有一组组件类型,它们的名称都在枚举中,如下所示:

type ComponentA = {
  attributes: {
    // ...
  }
}

type ComponentB = {
  attributes: {
    // ...
  }
}

现在,我想要做的是以某种方式定义类型组件,以便:

type Component = 
| {
    id: string;
    name: ComponentName.ComponentA;
    component: ComponentA;
  }
| {
    id: string;
    name: ComponentName.ComponentB;
    component: ComponentB;
  }
| // ...

有没有一种方法可以通过映射ComponentName多个枚举并将枚举属性匹配到组件类型名称来简化这种联合类型?

推荐答案

我认为,如果在组件名称和它们的属性之间有某种映射,那么可以使用以下帮助函数从该映射创建一个联合,

type Values<T> = T[keyof T];

Values从映射类型或对象的值生成联合类型.

enum ComponentName {
  ComponentA = "component.a",
  ComponentB = "component.b",
  ComponentC = "component.c",
}

type ComponentMappings = {
  [ComponentName.ComponentA]: {
    attributes: {
      className: string;
    };
  };
  [ComponentName.ComponentB]: {
    attributes: {
      className: string;
      foo: number;
    };
  };
  [ComponentName.ComponentC]: {
    attributes: {
      className: string;
    };
  };
};

type Values<T> = T[keyof T];

type Component = Values<{
  [K in ComponentName]: {
    id: string;
    name: K;
    component: ComponentMappings[K];
  };
}>;

const comopnentA: Component = {
  name: ComponentName.ComponentA,
  id: "component-a",
  component: {
    attributes: {
      className: "flex",
    },
  },
};

const componentB: Component = {
  name: ComponentName.ComponentB,
  id: "component-B",
  component: {
    attributes: {
      className: "flex",
      foo: 3,
    },
  },
};

TypesSript Playground

请注意,操场上的Prettify文字没有任何作用,当您将鼠标悬停在该文字上时,只会使其更具可读性.

Typescript相关问答推荐

如何根据参数的值缩小函数内的签名范围?

属性的类型,该属性是类的键,其值是所需类型

如何推断计算逻辑的类型

泛型类型联合将参数转换为Never

有条件地删除区分的联合类型中的属性的可选属性

有什么方法可以类型安全地包装import()函数吗?

如何将定义模型(在Vue 3.4中)用于输入以外的其他用途

有没有办法防止类型交集绕过联合类型限制?

->;Boolean类型的键不能分配给类型Never

如何从一个泛型类型推断多个类型

如何将通用接口的键正确设置为接口的键

如何在Type脚本中创建一个只接受两个对象之间具有相同值类型的键的接口?

类型脚本中函数重载中的类型推断问题

Typescript泛型调用对象';s方法

显式推断对象为只读

如何向我的自定义样式组件声明 custom.d.ts ?

我应该使用服务方法(依赖于可观察的)在组件中进行计算吗?

递归类型名称

Typescript 编译错误:TS2339:类型string上不存在属性props

从接口推断模板参数?