Home > Net >  TypeScript: Omit trailing parameter of generic function when its type is undefined
TypeScript: Omit trailing parameter of generic function when its type is undefined

Time:09-09

Is it possible to configure TypeScript to allow omitting the trailing parameter of a generic function if the trailing parameter's type is undefined (but not if it isn't)?

Example:

type Events = {
  readonly first: { readonly foo: string};
  readonly second: undefined;
}

const sendEvent = <Name extends keyof Events>(name: Name, payload: Events[Name]) => {
  console.log(`SEND EVENT "${name}"`, name, payload);
}

sendEvent('first', { foo: 'bar'}); // <-- OK

sendEvent('second', undefined); // <-- OK

sendEvent('first');  // <-- Error as expected, Events["first"] isn't undefined,
                     // that's good
sendEvent('second'); // <-- Error: 'Expected 2 arguments, but got 1.'
                     // would like to not have an error here, since
                     // Events["second"] is undefined

CodePudding user response:

If you only want to allow that when name is "second" and not when it's "first", you can't just use an optional parameter. But you can check if the payload is undefined, and if it is, make the second parameter optional by making the second element in the tuple optional:

const sendEvent = <Name extends keyof Events>(
    ...[name, payload]: (Events[Name] extends undefined ? [name: Name, payload?: Events[Name]] : [name: Name, payload: Events[Name]])
) => {

A bit long but it works, especially if you have more events.

Playground

  • Related