1

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
}
1
  • Oh this is a nice little template literal type question but I’m on mobile so someone else will almost certainly get here first! If not I’ll answer when I get a chance. Commented Feb 23, 2022 at 21:38

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Don't forget about the Capitalize type :)
Oh just saw he is expecting camel case, good point :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.