Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

591
Views
"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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!