christianost
christianost

Reputation: 212

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!

Upvotes: 0

Views: 36

Answers (1)

HannesT117
HannesT117

Reputation: 141

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;
}

Upvotes: 1

Related Questions