![](/img/trans.png)
[英]How to dynamically assign a name and type to unknown object property in Typescript
[英]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
實際上有一個更簡單的解決方法,你只需要使用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.