Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

95
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda