简体   繁体   中英

How to add type to a key in an object in typescript?

I have this type defined:

type PayloadTypes =
  | "VIEW_OFFER_DETAILS"
  | "ADD_TO_CART"
  | "MORE_INFO_ITEM"
  | "SHOW_ITEM_LOCATION";

I have an object which has a few keys but I don't want to define every key in the object, I just want the payload key to be defined

actions: [
  {
    type: "postback",
    text: "View details",
    payload: "VIEW_OFFER_DETAILS", // <- this one
    metadata: {
      userId,
      offer: JSON.stringify(offer)
    }
  }
]

How would you do in typescript?

type Action = { payload: PayloadTypes, [key: string]: any }
type ActionsList = Action[]

it's a very good way to incrementally type objects as you have a better understanding of their required structure. any named/defined params you type will have the indicated type, anything else will have any . Keep in mind this doesn't check against unknown object properties. So if Action can only have type , text , payload , and meta

action["somethingElse"] = 1

is perfectly valid given the above definition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM