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

594
Visualizações
"Type 'null' cannot be used as an index type" TS

I receive an error in Typescript code when I use my "language" const: "Type 'null' cannot be used as an index type."

const language =
      localStorage.getItem("language") !== null
        ? localStorage.getItem("language")
        : "en"; 
     
someText = someArray[language];

How can I fix it and why isn't working when I prevent language const from being null? (I know that index selector must by string/number)

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

The problem here (and the reason why TypeScript cannot infer the correct type of language) is that localStorage.getItem("language") is being evaluated two times, and it could as well - for what the compiler knows - return null upon the second invocation.

Use the ?? operator to exclude the possibility of language being null.

const language = localStorage.getItem("language") ?? "en"; 
someText = someArray[language];
over 4 years ago · Santiago Trujillo Relatório

0

You can just tweak your code a bit using Nullish Coalescing operator (??), which is basically what is share by GOTO. Just explaining it's name & working.

let someText = someArray[(localStorage.getItem("language") ?? "en")]

From MDN docs, The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

over 4 years ago · Santiago Trujillo 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