I'm currently working with the @octokit/webhooks.js
package that comes with advanced generic type constraints.
An example of how it is used:
webhooks.on('issue_comment.created', handlers.onIssueCommentCreated);
The function signature for this usage is defined as follows:
on: <E extends EmitterWebhookEventName>(event: E | E[], callback: HandlerFunction<E, TTransformed>) => void;
I am attempting to create a helper wrapper function around the on
function like the one below, but I am encountering issues:
function addWebhook<
E extends (EmitterWebhookEvent<EmitterWebhookEventName> & {
payload: { sender: User };
})['name'] &
`${string}.${string}`
>(webhooks: Webhooks, event: E | E[], callback: HandlerFunction<E, unknown>) {
webhooks.on(event, (options) => {
options.payload.sender; // <-- error: TS2339: Property 'sender' does not exist on type 'EventPayloadMap[Extract ]'.
});
}
My goal is to restrict this function to only accept values of E
that are constrained to be of type EmitterWebhookEventName
, and such that
EmitterWebhookEvent<E>['payload']['sender']
is of type User
. I am specifically facing challenges in implementing the 'such that' logic.
The key library types can be found here:
export declare type EmitterWebhookEventName = typeof emitterEventNames[number];
export declare type EmitterWebhookEvent<TEmitterEvent extends EmitterWebhookEventName = EmitterWebhookEventName> = TEmitterEvent extends `${infer TWebhookEvent}.${infer TAction}` ? BaseWebhookEvent<Extract<TWebhookEvent, WebhookEventName>> & {
payload: {
action: TAction;
};
} : BaseWebhookEvent<Extract<TEmitterEvent, WebhookEventName>>;
interface BaseWebhookEvent<TName extends WebhookEventName> {
id: string;
name: TName;
payload: WebhookEventMap[TName];
}