🚧withDefaults
Like Function.prototype.bind() but for a function that receives their parameters wrapped in an object.
Quick example
In greater detail
If you have a function with a set of parameters wrapped in an object, and you wish to call this function multiple times with the same value for one or more of the parameters, withDefaults
enables you to instantly generate a new function with these parameters already set so that you do not have to fill them in at every call.
Consider a function that takes two numbers as parameters and returns the sum of them.
Suppose we want to set the value of x
for example.
sumWd
is a proxy to our original function with x
set to 33
. withDefaults
first argument is the original function, and the second is an object with the parameters of the original function as properties. Naturally, the properties are inferred by typescript as shown below.
Now we can call sumWd
as many times as we want without having to set x
. Its value will always be 33
.
The value of result
will be 43
. Typescript infers the remaining value to be set:
Overwriting the injected value:
The type of x
in defaultsOverwrite
is [number] | undefined
so that undefined
cannot be assigned to x
if that is not its type.
Last updated