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.
0 Comments
Log in to join the conversation.No comments yet. Be the first to share your thoughts.