Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

221
Vistas
Typescript and text transformation (toLowerCase) is losing my type

Simple reproduction of my problem:

const demo = {
    aaa: 'aaa',
    bbb: 'bbb',
}

const input = 'AAA'

console.log(demo[input.toLowerCase()])

Playground

JS itself will work. It will change 'AAA' to 'aaa' which does exist in demo object. But TS throws error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ aaa: string; bbb: string; }'.

It's because it sees this value as any String, not 'aaa'. So TS does not allow to any text transformations in it's compiler?

This uppercase value comes from API (graphql enum) so I'm not able to change that. In other hand this object comes from library that uses normal pascalCase keys. So how I can connect both without TS complaying?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

What you really want to assert is that input.toLowerCase() results in a valid key for the map demo. You can express that like this:

console.log(demo[input.toLowerCase() as keyof typeof demo])

This should give you full type safety in the surrounding code. This is fine:

let ok: 'aaa' | 'bbb' = demo[input.toLowerCase() as keyof typeof demo]

But these are rejected:

let error1: 'aaa' = demo[input.toLowerCase() as keyof typeof demo]
let error2: 'ccc' = demo[input.toLowerCase() as keyof typeof demo]
about 4 years ago · Juan Pablo Isaza Denunciar

0

In addition to what @Thomas said in the above answer,

Whenever you use Typescript, You should clearly define the types of the variables and objects.

Check out the below code.

type d = {
    [key: string]: string
}

const demo: d = {
    aaa: 'aaa',
    bbb: 'bbb',
}

const input: string = 'AAA'

console.log(demo[input.toLowerCase()])
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda