Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
Assign an enum as the value of the key of an object type

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!