I would like to implement a function which takes an options
object with default values.
I know how to do that, but I want to impose that any field not specified by the user will attain the default value specified in the function header.
Here is what I have so far:
function func(options: {x: number; y: string;} = {x: 1, y: "1"}) {
const x: number = options.x != undefined ? options.x : 1;
const y: string = options.y != undefined ? options.y : "1";
console.log(x, y);
}
This works fine when I test this function on the output Javascript file:
func();
func({});
func({x: 0});
func({y: "2"});
func({x: 3, y: "4"});
Which results with:
1 '1'
1 '1'
0 '1'
1 '2'
3 '4'
However, it feels a little hacky (in particularly, the fact that I need to specify each one of the default values in two different places).
Is there a known design-pattern for this in Typescript?
No need to have default values in two places, you can shorten it up like this:
function func({ x = 1, y = "1" }: { x?: number; y?: string; } = {}) {
console.log(x, y);
}
func();
func({});
func({ x: 0 });
func({ y: "2" });
func({ x: 3, y: "4" });
Or even shorter, if you don't need an explicit type:
function func({ x = 1, y = "1" } = {}) {
console.log(x, y);
}
Results:
1 '1'
1 '1'
0 '1'
1 '2'
3 '4'