如何在Typescript中以字符串形式获取接口的属性名/键名



目前使用Slacks API,有些实例中我使用字符串发送JSON请求,这些字符串稍后作为属性名称返回。

我想要一个接口,并将其属性名之一作为字符串发送。然后正确键入返回的对象。我不想不得不处理"魔术串";或者我必须与接口保持同步的常量。

快速示例:

// 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;
}

我的问题是这个接口绑定到了我发送的字符串。

有没有办法让我拿到钥匙/财产;specialProperty";作为字符串从我的SpecialPropertyInterface?

我最终通过使用;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";

下面是一个尝试。

首先,将as const作为后缀添加到request对象的声明中:

const request = {
actionId: "specialProperty"
} as const;

因此,actionId属性的类型是文字("specialProperty"(,而不是string:

type RequestActionId = typeof request["actionId"] // "specialProperty"

现在,我们可以在映射索引签名中使用它:

type SpecialPropertyInterface = {
[propName in RequestActionId]: string; // specialProperty: string
}

游乐场链接

最新更新