How to use a string to index a json object in typescript

4k views Asked by At

new to deno/typescript, the main idea is variable kindx will be from the command line and some info in the types object will be shown, but always get this error:

error: TS7053 [ERROR]: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ A: string; B: string; }'.
  No index signature with a parameter of type 'string' was found on type '{ A: string; B: string; }'.
let obj = types[kindx]

here is the code:

const types  = {
    A: 'Apple',
    B: 'Banana'    
}

let kindx = 'B'  //  will be from Deno.args[0]
//const kindx  = 'B'  // this works

let obj = types[kindx]
console.log(obj)

2

There are 2 answers

0
johannchopin On BEST ANSWER

A let variable can be change on runtime so TypeScript implicitly give him the type any. To fix that, you need to define the type of kindx:

type TypeKey = 'A' | 'B'  // create some types to define the 'types' object
type Type={ [key in TypeKey]: string }

const types: Type  = {
    A: 'Apple',
    B: 'Banana'    
}

let kindx: TypeKey = 'B'  // explicit the type of 'kindx'

let obj = types[kindx] // no more complain
0
AudioBubble On

The issue is that let kindx = "B" is of type string, while const kindx = "B" is of type "B"

let doesn't ensure that the variable cannot be modified after its initialization, const does. With let, typescript widens the type to string automatically

There's a bunch of ways to fix it:

let kindx: keyof typeof types = 'B' // ensures that kindx can only be a key of types

let kindx: "B" = "B" // technically not a const, but nothing other than "B" is assignable to kindx

const kindx = "B" // const's cannot be modfied, value "B" is ensured