![](/img/trans.png)
[英]Typescript: How to reference property name in an string index signature definition in an interface
[英]How to get the property name / key name of an interface as a string in Typescript
目前正在使用 Slacks API 並且在某些情況下我發送帶有字符串的 JSON 請求,這些字符串稍后會作為屬性名稱返回。
我想要一個接口並將其屬性名稱之一作為字符串發送。 然后正確輸入返回的 object。 我不想處理必須與界面保持同步的“魔術字符串”或常量。
快速示例:
// This is the request I send out to Slack
const request = {
actionId: "specialProperty"
};
// And Slack might give me this object at a later point
const incomingWebhook = {
specialProperty: "Value I want to read"
}
我可以很容易地用一個界面來輸入這個
interface SpecialPropertyInterface {
specialProperty: string;
}
我的問題是這個接口綁定到我發送的字符串。
有沒有辦法讓我從我的 SpecialPropertyInterface 獲取密鑰/屬性“specialProperty”作為字符串?
這是一個嘗試。
首先,將as const
作為后綴添加到您的request
object 的聲明中:
const request = {
actionId: "specialProperty"
} as const;
因此, actionId
屬性的類型是文字( "specialProperty"
)而不是string
:
type RequestActionId = typeof request["actionId"] // "specialProperty"
現在,我們可以在映射索引簽名中使用它:
type SpecialPropertyInterface = {
[propName in RequestActionId]: string; // specialProperty: string
}
我最終通過使用“keyof”解決了我的問題。 不是最優的,但我得到了一個基於接口屬性的類型安全字符串。
我有兩個嵌套鍵,所以我將它們分成兩個接口,並使用 keyof 來獲取每個接口的屬性字符串。
export interface HoursBlock {
hours: HoursBlockAction;
}
export interface HoursBlockAction {
hoursAction: {
// eslint-disable-next-line camelcase
selected_option: {
value: string;
};
};
}
...
// This string will only be valid if you write the name of the property.
const hoursBlockId: keyof HoursBlock = "hours";
const hoursActionId: keyof HoursBlockAction = "hoursAction";
// If you type a different string you will trigger an error.
// Type '"wrong"' is not assignable to type '"hours"'.ts(2322)
const wrongHoursBlockId: keyof HoursBlock = "wrong";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.