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

214
Visualizações
Create function in Typescript that given an object will return an object that has keys and values derived from the values of the given object

I'm trying to wrap my head around types in Typescript. In general it's going well but I'm struggling to convert this function from Javascript to Typescript.

export function keyed(object, key, value) {
  const newKey = object[key];
  const newValue = object[value];
  const newObject = {};
  newObject[newKey] = newValue;
  return newObject;
};

This is my attempt so far:

type ValueOf<T> = T[keyof T];
export function keyed<T, K extends keyof T>(object: T, key: K, value: K): { [key: ValueOf<T>]: ValueOf<T> } {
  const newKey: ValueOf<T> = object[key];
  const newValue: ValueOf<T> = object[value];
  const newObject: { [key: ValueOf<T>]: ValueOf<T> } = {};
  newObject[newKey] = newValue;
  return newObject;
};

But, I'm getting a few errors like:

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

and

Type 'ValueOf<T>' cannot be used to index type '{}'.ts(2536)

I've tried to use underscores DefinitelyTyped definitions to help out over here, since they do quite a bit of these operations but I haven't had any luck. Is it impossible?

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