Parameters, but only sometimes
16 August 2024
Updated: 24 August 2024
Ran into this question today and I thought it would be a nice little example to document:
I have the following function doWork
that is generic:
This function can be called in any of the following ways:
In the above usage, we want to make it so that users of this function need to provide the data
parameter when calling the function when the type is provided. Now, a simple solution could be to define our function as follows:
The problem is that it’s a bit ugly for cases where we want to allow T
as undefined
, because you now have to do this:
So the issue here is that we only want to make the data
parameter required when T
is not undefined
, there’s a lot of funny stuff you can try using generics and other weird typescript notation, but simply defining the necessary overloads for our method works:
Now, having defined those function overloads, we can use the function and it works as expected:
The added benefit of this method is that we can also write the doc comments for each implementation separately which can be a nice way for us to give additional context to consumers. It’s kind of like having two specialized functions without the overhead of having to implement them independently