如何在 TypeScript 中动态访问对象属性

luk*_*srw 12 node.js typescript

我一直在尝试将现有项目(从 Node.js)转换为 TypeScript。

对于上下文,我使用的是 http-status 包(https://www.npmjs.com/package/http-status

我试图将变量传递到它们的默认导出中,但出现错误:

import status = require("http-status");

status.OK; // this works
status["OK"] // this also works

let str = "OK";
status[str]; // error
Run Code Online (Sandbox Code Playgroud)

错误:

元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引“HttpStatus”类型。
在类型 'HttpStatus' 上找不到带有类型为 'string' 的参数的索引签名。


我如何将这种用法转换为 TypeScript?

Gui*_* F. 21

"OK"是一个字符串,并且str在您的代码中隐式地采用类型字符串。

当您尝试访问对象的属性时,您需要使用类型keyof。然后,TypeScript 知道您分配的不是随机字符串;您正在分配与对象的属性(键)兼容的字符串。

此外,由于status是变量,而不是类型,因此您需要使用typeof.

尝试:

let str = "OK" as keyof typeof status;
status[str]; // 200
Run Code Online (Sandbox Code Playgroud)

或更干净:

type StatusKey = keyof typeof status;
let str: StatusKey = "OK";
status[str]; // 200

// and to answer the question about reversal
status[status.OK as StatusKey]; // OK
Run Code Online (Sandbox Code Playgroud)

请参阅:https : //www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-and-lookup-types

  • 经过大量搜索,这就是我所需要的。越来越喜欢TS了。虽然这有点冗长,但我知道为什么需要如此。还是很棒。谢谢 (2认同)

小智 6

我必须从对象访问二级动态密钥。

const myObj = {
  "address": {
    "street": "Main ave",
    "city": "NYC"
  }
}

secondLevelDynamic(field: string) {

  let dynamicKey = field as keyof myObj;

  let myProp = this.myObj['address'];
  let myDynamicPropValue = myProp[dynamciKey]
}
Run Code Online (Sandbox Code Playgroud)