Home > Mobile >  "Type 'null' cannot be used as an index type" TS
"Type 'null' cannot be used as an index type" TS

Time:11-30

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)

CodePudding user response:

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];

CodePudding user response:

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.

  • Related