簡體   English   中英

如何動態訪問 TypeScript 中的 object 屬性

[英]How to dynamically access object property in TypeScript

我一直在嘗試將現有項目(從 Node.js)轉換為 TypeScript。

對於上下文,我使用的是 http-status package ( 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

錯誤:

元素隱式具有“任何”類型,因為“字符串”類型的表達式不能用於索引類型“HttpStatus”。
在“HttpStatus”類型上找不到具有“字符串”類型參數的索引簽名。


如何將此用法轉換為 TypeScript?

"OK"是一個字符串,而str隱含地采用代碼中的類型字符串。

當您嘗試訪問對象的屬性時,您需要使用keyof類型。 TypeScript 然后知道您沒有分配隨機字符串; 您正在分配與 object 的屬性(鍵)兼容的字符串。

此外,由於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

實際上有一個更簡單的解決方法,你只需要使用const assertion

這是修復:

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

游樂場鏈接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM