如何在打字稿中将类型添加到对象中的键?
How to add type to a key in an object in typescript?
我定义了这个类型:
type PayloadTypes =
| "VIEW_OFFER_DETAILS"
| "ADD_TO_CART"
| "MORE_INFO_ITEM"
| "SHOW_ITEM_LOCATION";
我有一个有几个键的对象,但我不想定义对象中的每个键,我只想定义 payload
键
actions: [
{
type: "postback",
text: "View details",
payload: "VIEW_OFFER_DETAILS", // <- this one
metadata: {
userId,
offer: JSON.stringify(offer)
}
}
]
你会如何打字?
type Action = { payload: PayloadTypes, [key: string]: any }
type ActionsList = Action[]
这是一种增量键入对象的好方法,因为您可以更好地了解它们所需的结构。您键入的任何 named/defined 参数都将具有指示的类型,其他任何参数都将具有 any
。请记住,此 不会 检查未知对象属性。所以如果Action
只能有type
、text
、payload
和meta
action["somethingElse"] = 1
根据上述定义完全有效。
我定义了这个类型:
type PayloadTypes =
| "VIEW_OFFER_DETAILS"
| "ADD_TO_CART"
| "MORE_INFO_ITEM"
| "SHOW_ITEM_LOCATION";
我有一个有几个键的对象,但我不想定义对象中的每个键,我只想定义 payload
键
actions: [
{
type: "postback",
text: "View details",
payload: "VIEW_OFFER_DETAILS", // <- this one
metadata: {
userId,
offer: JSON.stringify(offer)
}
}
]
你会如何打字?
type Action = { payload: PayloadTypes, [key: string]: any }
type ActionsList = Action[]
这是一种增量键入对象的好方法,因为您可以更好地了解它们所需的结构。您键入的任何 named/defined 参数都将具有指示的类型,其他任何参数都将具有 any
。请记住,此 不会 检查未知对象属性。所以如果Action
只能有type
、text
、payload
和meta
action["somethingElse"] = 1
根据上述定义完全有效。