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.

3
  • Please provide more information about constraints. Keys and values of Enum are the same by purpose? This syntax Enum1 = 'Enum 1' is invalid in object literals. Please share reproducible example without type errors Commented Jan 4, 2022 at 14:28
  • Does this work for you? Commented Jan 4, 2022 at 14:35
  • @captain-yossarian The key and values will be the same. I have updated the code. Commented Jan 4, 2022 at 16:16

1 Answer 1

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).

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

1 Comment

This is exactly what I was looking for. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.