Home > Back-end >  Create type keys dynamically in Typescript
Create type keys dynamically in Typescript

Time:02-24

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
}

CodePudding user response:

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

  • Related