It's best practice in case you have many parameters to let the user insert only few parameters and not in specific order.
For example, bad practice:
foo(a?, b=1, c=99, d=88, e?)
foo(null, null, null, 3)
Since you have to supply all the parameters before the one you actually want (d).
Good practice to use is:
foo({d=3})
The way to do it is through interfaces.
You need to define the parameter as an interface like:
interface Arguments {
a?;
b?;
c?;
d?;
e?;
}
And define the function like:
foo(arguments: Arguments)
Now interfaces variables can't get default values, so how do we define default values?
Simple, we define default value for the whole interface:
foo({
a,
b=1,
c=99,
d=88,
e
}: Arguments)
Now if the user pass:
foo({d=3})
The actual parameters will be:
{
a,
b=1,
c=99,
d=3,
e
}
Another option without declaring an interface is:
foo({
a=undefined,
b=1,
c=99,
d=88,
e=undefined
})
Follow Up:
In the previous function definition we define defaults for the fields of the parameter object, but not default for the object itself.
Thus we will get an extraction error (e.g. Cannot read property 'b' of undefined
) from the following call:
foo()
There are two possible solutions:
1.
const defaultObject = {a=undefined, b=1, c=99, d=88, e=undefined}
function foo({a=defaultObject.a, b=defaultObject.b, c=defaultObject.c, d=defaultObject.d, e=defaultObject.e} = defaultObject)
function foo(object = {}) {
object = { b=1, c=99, d=88, ...object }
//Continue the function code..
}
Follow Up:
If you need types & default values (and you don't want to declare an interface), you can write:
function foo(params: {a?: string, b?: number, c?: number, d?: number, e?: string}) {
params = { b:1, c:99, d:88, ...params }
//Continue the function code..
}
IX
short for? Code on stack overflow should generally use real variable names.