动态密钥类型与打字稿中的其他密钥类型
如何在打字稿中使用其他静态密钥类型制作动态密钥。 对于例如。
{
"organizationId": "NEW_ORG",
"displayName": "Test Display",
"photo": null,
"1645661283562_tab": {
"isMove": false,
"tabName": "Activities",
}
}
我有其他键的静态类型,但 1645661283562_tab 是动态的,如何为这种类型的对象创建类型?
type RecordDto = {
organizationId?: string;
displayName?: string;
photo?: string | null;
[key: string]: { isMove:boolean, tabName: string };
};
这是行不通的。有什么解决办法吗?
How to make dynamic key with other static Key types in typescript.
For Eg.
{
"organizationId": "NEW_ORG",
"displayName": "Test Display",
"photo": null,
"1645661283562_tab": {
"isMove": false,
"tabName": "Activities",
}
}
I have a static type for other keys, but 1645661283562_tab is dynamic, how to make type for this type of object?
type RecordDto = {
organizationId?: string;
displayName?: string;
photo?: string | null;
[key: string]: { isMove:boolean, tabName: string };
};
this is not working. any solutions ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
理想情况下,将它们拆分为
RecordDto
上的子对象,而不是直接将它们放在RecordDto
上。 (例如,类型为Record
的tabs
属性。)但是如果您不能或不这样做不想这样做:只要您可以根据名称区分索引键与其他键,只需稍加调整即可正常工作。例如,您的密钥是一个数字,后跟
_tab
并且您的其他属性都不符合该模式,因此 模板文字类型 适用于索引签名的键,并将其与其他属性名称区分开来:Playground 链接
如果您以字符串形式接收这些值,并且需要使用它们对类型进行索引,则需要告诉 TypeScript 它们可以有效用作索引键。为此,您可以使用类型保护函数:
...或类型断言函数:
您可以像这样使用它们:(
如果使用类型保护函数;该键在
true
分支中有效。)游乐场链接
Ideally, split those off into a sub-object on
RecordDto
instead of having them directly onRecordDto
. (For instance, atabs
property with the typeRecord<string, {isMove: boolean; tabName: string; }>
.) But if you can't or don't want to do that:Provided you can distinguish the index keys from the other keys based on their name, it will work as you have it with a slight tweak. For instance, your key is a number followed by
_tab
and none of your other properties fits that pattern, so a template literal type works for the key of the index signature and differentiates those from the other property names:Playground link
If you're receiving these values as strings and need to use them to index into the type, you'll need to tell TypeScript they're valid for use as index keys. To do that, you can use either a type guard function:
...or a type assertion function:
You use them like this:
(You'd use
if (isValidTabName(tabKey))
if using the type guard function; the key is valid in thetrue
branch.)Playground link