简体   繁体   English

在 Typescript 中动态创建类型键

[英]Create type keys dynamically in Typescript

I want to generate the type keys from a combination of other type's key, like create dynamically object's keys.我想从其他类型的键的组合中生成类型键,比如动态创建对象的键。

type Swatch = {
  dark: string;
  light: string;
};

type ColorTheme = {
  primary: Swatch;
  secondary: Swatch;
};

// The result should be
type CombineType: {
  // This keys are dinamically created as a combinatino of Swatch and ColorTheme keys

  // primaryDark: string
  // secondaryDark: string
}

You can achieve this by creating some kind of "generator" generic type that will give you the expected output.您可以通过创建某种“生成器”泛型类型来实现这一点,它将为您提供预期的 output。

type First = {
  foo: string;
  bar: string;
};

type Second = {
  first: string;
  second: string;
}

type JoinKeys<FK, SK> = 
  FK extends string ?
    SK extends string ?
      `${FK}${Capitalize<SK>}`
    : never
  : never;

type CombineTypes<F,S> = {
  [key in JoinKeys<keyof F,keyof S>]: string;
};

type Test = CombineTypes<First, Second>;

Type JoinKeys simply combines passed in key values.类型JoinKeys只是组合传入的键值。 Type CombineTypes is a simple generic type that takes two params and outputs a type, where key is joined by keyof both passed params类型CombineTypes是一个简单的泛型类型,它接受两个参数并输出一个类型,其中键由两个传递的参数的键keyof

You should extend these a bit to make sure only objects can be passed in and to have proper type coverage:)您应该稍微扩展这些以确保只能传入对象并具有适当的类型覆盖率:)

Here is working example in Typescript Playground这是Typescript 游乐场中的工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM