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

117
Visualizações
How can I specify types on a camel to snake case conversion function

I have a function that converts the case of a target string, array, or object from camel case to snake case.

convertCamelToSnake (target) {
  // Complex logic to convert target depending on what type it is
  return convertedTarget
}

I want to specify types on this function using a Generic like so:

convertCamelToSnake <T>(target: T):T {
  // Complex logic to convert target depending on what type it is
  return convertedTarget
}

This works for strings and arrays, but we convert the keys of a given object to snake case. But typescript doesn't realize this and assumes that the keys remain the same because we declare that we are returning T.

How can I retain the ability to know the type that is returned. I.e. string, array, object, while leaving the keys of the dictionary ambiguous?

For instance let's say we pass in:

const a = { helloWorld: "bob", age: 21 }
a = convertCamelToSnake(a); // { hello_world: "bob", age: 21 };
a.hello_world; // Property 'hello_world' does not exist on type 

How can we make it so we're allowed to access the hello_world property after converting the object, while also still being able to infer that the return value is of type object (since we could for instance also be passing in an array into this function)?

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