簡體   English   中英

打字稿:在類型上動態構造屬性名稱

[英]Typescript: dynamically constructing property name on type

當然,這是基本的 TS,但我找不到語法。

我有一個類型:

type MyType = {
   prop1: string;
   prop2: string;
}

現在在一個函數中,我有一個 MyType 類型的變量,但我需要動態獲取其上特定屬性的值,例如:

const myMethod = (typeX: MyType, num: number) => {
    const property1 = typeX['prop${num}`]; // problem line!
}

我看到的打字稿錯誤是:

TS7053 Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'MyType'. No index signature with a parameter of type 'string' was found on type 'MyType'

將其更改為typeX['prop1']工作正常。

如何將該字符串轉換為 MyType 上的屬性?

您將需要在此處使用類型斷言(類似於其他語言中的強制轉換,但沒有運行時語義):


type MyType = {
   prop1: string;
   prop2: string;
}

const myMethod = (typeX: MyType, num: number) => {
    const property1 = typeX[`prop${num}` as keyof MyType]; 
}

游樂場鏈接

暫無
暫無

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

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