Johhan Santana
Johhan Santana

Reputation: 2415

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?

Upvotes: 0

Views: 6474

Answers (1)

Tyler Sebastian
Tyler Sebastian

Reputation: 9458

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.

Upvotes: 3

Related Questions