简体   繁体   中英

Types for an object as function argument which should not contain specific keys

I have an wrapper function around a tracking-library which sets some of the required properties. My wrapper function excepts an arbitrary payload which I will pass down to the tracking function. In an example this would look like the folllowing:

// my tracking function setting the fictional & required "time" property as default
const track = (payload) => { trackingLib.track({ time: Date.now(), ...payload}) }

// can later be used like
track({ view: 'settings', action: 'delete-account' })

I now want to forbid keys like time (or other pre-defined keys) to be used in the payload by the users of my function:

track({ time: 1337 }) // should error
track({ timestamp: 1337 }) // should not error

How can I type payload to allow "every" string as key (values don't matter) except some pre-defined ones (which I know ahead, so they don't need to be dynamic)?

Can someone point me in the right direction? Thanks for your help!

Fells a little bit hacky, but the following could work for most use cases. Another con is that your editor will probably suggest time as a property. Still the best (and easy to implementable) solution I can think of though:

type Payload {
  [key: string]: unknown;
  time?: never;
}

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