我一直在尝试将现有项目(从 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/