I'd like to avoid introducing TypeScript because of the introduction of a build step and all of it's extra machinery, so I want to use JSDoc to receive much of the same benefit.
TypeScript has something called Tagged Unions, in which we can discriminate between versions of similar objects based on the value of a tag key.
This is possible in JSDoc like so, but the literal union here can be quite verbose if extended to several dozen variants.
/**
* @typedef {Object} ReceiveResponse
* @property {String} foo
*
* @typedef {Object} ReceiveEvent
* @property {'receive'} type
* @property {ReceiveResponse} data
*/
/**
* @typedef {Object} SendResponse
* @property {String} bar
*
* @typedef {Object} SendEvent
* @property {'send'} type
* @property {SendResponse} data
*/
/**
* @typedef {{type: 'receive', send: (event: ReceiveEvent) => void}} ReceiveEventHandler
* @typedef {{type: 'send', send: (event: SendEvent) => void}} SendEventHandler
*/
/**
* @param {ReceiveEventHandler | SendEventHandler} handler
*/
function on(handler) {
//...
}
on({type: 'send', send: (event) => {
event.data //(property) data: SendResponse
}})
Is it possible to introduce some form of inheritance, such we can have a root EventHandler object and simply refer to it?