简体   繁体   中英

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.

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. Type CombineTypes is a simple generic type that takes two params and outputs a type, where key is joined by keyof both passed params

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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