Search code examples
typescript

Generate a string type from two objects keys separated by a dot


I have two constants, something like

const colors = {
  a: '',
  b: '',
  c: '',
};

const variations = {
  100: '',
  200: '',
  300: '',
}

And I want to create a type from these two objects keys that accepts a.100, a.200, a.300, b.100, b.200, b.300, c.100 and so on, something like

const colorVariations: ThisTypeNameHere = 'a.100'; // good
const colorVariations: ThisTypeNameHere = 'b.200'; // good
const colorVariations: ThisTypeNameHere = 'c.100'; // good
const colorVariations: ThisTypeNameHere = 'a200';  // bad
const colorVariations: ThisTypeNameHere = 'a.950'; // bad

Solution

  • Can be done using template literal types!

    const colors = {
      a: '',
      b: '',
      c: '',
    };
    
    const variations = {
      100: '',
      200: '',
      300: '',
    };
    
    // Extracting keys from colors and variations
    type ColorKeys = keyof typeof colors;
    type VariationKeys = keyof typeof variations;
    
    // Creating the combination type
    type ColorVariations = `${ColorKeys}.${VariationKeys}`;
    
    const colorVariations: ColorVariations = 'a.100'; // good
    const colorVariations1: ColorVariations = 'b.200'; // good
    const colorVariations2: ColorVariations = 'c.100'; // good
    const colorVariations3: ColorVariations = 'a200';  // bad (TypeScript will throw an error)
    const colorVariations4: ColorVariations = 'a.950'; // bad (TypeScript will throw an error)