如何使用字符串索引打字稿中的 json 对象

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

deno/typescript 的新手,主要思想是变量 kindx 将来自命令行,并且会显示 types 对象中的一些信息,但总是会出现此错误:

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]

代码如下:

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)

问题是 let kindx = "B"string 类型,而 const kindx = "B""B"

类型

let 不能确保变量在初始化后不能被修改,const 可以。使用 let,typescript 自动将类型扩展为 string

有很多方法可以修复它:

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

A let 变量可以在运行时更改,因此 TypeScript 隐式地​​给他类型 any。要解决这个问题,您需要定义 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