Use generics to dynamically specify the number, and type, of arguments to functions

You can run into a problem with TypeScript when you start trying to deal with optional arguments that you want to be optional in some cases and not optional in others.

Here we've got a sendEvent function which takes in the Event type, and an optional payload.


export type Event =
| {
type: "LOG_IN"
payload: {
userId: string
}
}
| {
type: "SIGN_OUT"
}
const sendEvent = (eventType: Event["type"], payload?: any) => {}

And this payload is not really optional because we need to pass it when we pass LOG_IN, but not pass it when we pass SIGN_OUT.

We also need a way to handle invalid payloads.

So how do we handle this?. How do we make the function arguments different case by case?

Check out this one I created earlier. This sendEvent now takes in a generic, which is the Event type. And here we do some crazy stuff based on that type.


const sendEvent = <Type extends Event["type"]>(
...args: Extract<Event, { type: Type }> extends { payload: infer TPayload }
? [Type, TPayload]
: [Type]
) => {}

We extract out the event and the ones matching { type: Type }. So essentially we check if there's a payload there and we infer the payload.

And if there is a payload on the Event type that we've specified, we say these are the two arguments, Type and TPayload. Otherwise, it's just Type.

And this means that when we go to sendEvent, then we've got LOG_IN or SIGN_OUT. When we write another sendEvent we see that that we get that nice autocomplete for us.


sendEvent("LOG_IN", {
userId: "123",
})

But there's an issue here. On the auto-complete you actually have arg0 and arg1, which you don't want. So you can actually use a named tuple here, and specify the names of the arguments.


const sendEvent = <Type extends Event["type"]>(
...args: Extract<Event, { type: Type }> extends { payload: infer TPayload }
? [type: Type, payload: TPayload]
: [type: Type]
) => {}

And what you'll see are the proper argument names registered. So it's kind of a verbose syntax, but it's very, very useful in some specific cases.

Transcript

0:00 You can run into a problem with TypeScript when you start trying to deal with optional arguments that you want to be optional in some cases and not optional in others. Here, we've got a sendEvent function which takes in the event type, which is this event type up here, and an optional payload.

0:16 This payload is not really optional, because we need to pass it when we pass login, but not pass it when we pass sign out, as you can see here. These ones should error, because we shouldn't even be able to pass an empty payload here. We should not be able to pass an incorrect payload.

0:32 How do we handle this? How do we make the function arguments different case-by-case? Well, I'm going to do a little bit of, here's one I created earlier. This sendEvent now takes in a generic, which is the event type. Here, we do some crazy stuff based on that type.

0:49 We extract out the event, and we extract out the event and the ones matching this. Essentially, this, we check if there's a payload there, and we infer the payload. If there is a payload on the event type that we've specified, we say these are the two arguments, type and T payload. Otherwise, it's just type.

1:10 This means that, when we go to send an event -- whoops, sendEvent -- then we've got log in or sign out. Based on the one we choose -- let's say log in -- then we need to specify the payload, and it's all autocompleted for us, but there's an issue here which is on the autocomplete, you actually have arg zero and argos one, which you don't want.

1:31 You can actually use a named tuple here, and you could say type, type, payload, payload, and this is type, type. Now, what you'll see is it's properly registered as the name of the argument there. It's quite verbose, this syntax, but it's very, very useful in some specific cases.

You can use generics to dynamically specify the number, and type, of arguments to functions.

Here, we create a sendEvent function which only asks for a payload if it's present on the event you're sending.

Discuss on Twitter

More Tips

Assign local variables to default generic slots to dry up your code and improve performance