0

Below is my Enum:

export enum MyEnum {
  Enum1 = 'Enum 1',
  Enum2 = 'Enum 2',
  Enum3 = 'Enum 3',
  Enum4 = 'Enum 4',
  Enum5 = 'Enum 5',
}

I want to create a type for the example object shown below:

const testData = {
  test1: {
    Enum1: 'Enum 1',
    Enum2: 'Enum 2',
  },
  test2: {
    Enum1: 'Enum 1',
    Enum2: 'Enum 2',
    Enum3: 'Enum 3',
    Enum4: 'Enum 4',
  },
  test2: {
    Enum1: 'Enum 1',
    Enum2: 'Enum 2',
    Enum4: 'Enum 4',
  },
};

So far, I could come up with:

type FilteredBuyableMethods = {
  [key: string]: Partial<{
    [key in MyEnum]: string
  }>
};

How can I replace the string in [key in MyEnum]: string with the exact value of the key?

So, if the key is Enum1, the value for it should only be 'Enum 1' and so on.

Also, the value (object with enum key and value) attached to the keys (e.g test1, test2) available in testData should be the ones from enum MyEnum. Not necessarily all values from the enum MyEnum should be present (partials) but one should not be able to add any random key-value pairs apart from the enum key-value pairs. Thanks in anticipation.

shet_tayyy
  • 5,366
  • 11
  • 44
  • 82

1 Answers1

2

Using the tricks from Use Enum as restricted key type in Typescript and Typescript: string literal union type from enum, you can construct a mapped type as follows:

type FilteredBuyableMethods = {
  [key: string]: Partial<{
    [key in keyof typeof MyEnum]: `${typeof MyEnum[key]}`
  }>
};

Notice the typeof MyEnum[key] parses as (typeof MyEnum)[key].
(online playground)

This will both prevent wrong keys (that are not keys of the enum), as well as wrong value (that don't fit to their key respectively).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375