【问题标题】:How to dynamically access object property in TypeScript如何在 TypeScript 中动态访问对象属性
【发布时间】:2020-10-07 19:46:12
【问题描述】:

我一直在尝试将现有项目(从 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”类型上找不到带有“字符串”类型参数的索引签名。


如何将此用法转换为 TypeScript?

【问题讨论】:

    标签: node.js typescript


    【解决方案1】:

    其实有一个更简单的解决方法,你只需要使用const assertion。

    解决方法如下:

    const str = "OK" as const; // <-- add "as const", now `str` has type of "OK" instead of `string`
    status[str]; // No more error!
    

    Playground link.

    【讨论】:

    • const str = "OK" 是一种更优雅的编写方式。如果 OP 询问如何使用动态变量进行操作,他可能不需要常量。
    【解决方案2】:

    "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

    【讨论】:

    • 谢谢,虽然我遇到了更多问题。 status.OK 返回一个数字 200,但是字符串“200”作为状态对象的键存在。我如何将一个转换为另一个?所以该函数(由于您的回答)正确地需要一个 200 的字符串,执行 String(status.OK) 似乎不能满足这一点。
    • 您可以使用as StatusKey 投射第一个答案。它仍然不是 String,它是 StatusKey,告诉 TypeScript。
    • @GuillaumeF。感谢您的回答,我能够解决过去 3-4 天困扰我的一个阻止程序!非常感谢!
    猜你喜欢
    • 2021-11-27
    • 2021-02-27
    • 2011-06-15
    • 1970-01-01
    • 2019-09-01
    • 1970-01-01
    • 2011-08-10
    • 1970-01-01
    相关资源
    最近更新 更多