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

606
Visualizações
Typescript: Generic enum types as index for another type

I'm trying to create an indexed type whose index are the values of an enum BUT the enum comes from a generic argument.

export type EnumMap<TEnum extends string | undefined = undefined> = {
  [key: TEnum]: ValueClass;
}
export type EnumMap<TEnum extends string | undefined = undefined> = {
  [key: keyof TEnum]: ValueClass;
}

Both of those implementations shows the error:

An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.

When I implement it as a mapped object as suggested:

export type EnumMap<TEnum extends string | undefined = undefined> = {
  [TEnumKey in keyof TEnum]: ValueClass;
}

It doesn't show any errors at the definition but it only accepts TEnum instances as the value. It shows this error when I try to instantiate an EnumMap.

Type '{ "test": ValueClass; }' is not assignable to type 'TestEnum'.

I'm using this enum as a test:

export enum TestEnum {
  test = 'test'
}

Is there any way to use a generic enum as a type's index?

PS.: I understand I can implement it using string as the key, but I want to tie the indexes to the enum values;

export type EnumMap = {
  [key: string]: ValueClass;
}
const map: EnumMap = { [TestEnum.test]: {...} }; // works fine
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Does this work for you?

enum Enum {
  "ABC" = "abc",
  "CDE" = "cde"
}

export type EnumMap<TEnum extends string = Enum> = {
  [key in TEnum]?: string;
}

const map: EnumMap = { [Enum.ABC]: "123" };

Since TEnum is a string union, you can use it as [key in TEnum] inside the index signature.

I am not sure why you used string | undefined for TEnum...

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