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

240
Visualizações
How do I fix this Typescript error when accessing optional properties in a mapped type?

I'm using a generic mapped type to add meta data to entity types. I get an error when I try to access optional properties in the meta type.

Type definitions:

interface Entity {
  id: number;
  title: string;
}

interface EntityMeta<T> {
  required: {
    [Property in keyof T]?: true;
  };
}

Use:

const entity: Entity = {
  id: 1,
  title: "test"
};

const meta: EntityMeta<Entity> = {
  required: {
    id: true
  }
};

Object.entries(entity).forEach(([key, value]) => {
  console.log(`${key} = ${value}, Is required: ${meta.required[key] ? 'yes' : 'no'}`)
})

The semantics here is that I want to be able to say which subset of entity properties are required and then to access this meta data when I map over entity properties later.

The error is on that last line: meta.required[key]

Error message:

TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ id?: true | undefined; title?: true | undefined; }'.   No index signature with a parameter of type 'string' was found on type '{ id?: true | undefined; title?: true | undefined; }'.

It's easy to access these properties directly:

const isIdRequired = meta.required.id;

But, I need to access them dynamically via a string key.

How do I best fix this in Typescript?

Thanks,

about 4 years ago · Juan Pablo Isaza
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