node.js - 如何在 TypeScript 中动态访问对象属性

标签 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

错误:

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

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

最佳答案

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

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

此外,由于 status是变量,不是类型,需要用typeof提取它的类型.

尝试:

let str = "OK" as keyof typeof status;
status[str]; // 200

或更干净:
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

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

关于node.js - 如何在 TypeScript 中动态访问对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62438346/

相关文章:

typescript - NextJS : Run a Typescript script on the server

types - 是否可以在 TypeScript 的类中定义类型(字符串文字联合)?

javascript - @Output childEvent 未初始化

javascript - 无法让 Node 调试工作

node.js - Mongoose 或带日期的运算符

javascript - 将元数据插入实时视频流

javascript - Mongoose/JS - 跳出代码,跳过任何 then block

javascript - 无法读取未定义的属性 'login' - 测试 spy - Angular2+

node.js - 无法加载资源: the server responded with a status of 426 (Upgrade Required)

typescript - 如何使用接口(interface)使 API 响应类型安全/声明? typescript