In my TypeScript method, I am using named parameters like this
public foo({x, y, z , m , n} : {x:string, y: number, z: number, m?:string, n?:number}) {
}
The parameters m
and n
will be provided from another object like
const defaults = { m : 'M', n :10, o:6 }
Now, I want to call the foo
function like below and automatically add default parameters without explicitly passing them
foo({x:'x', y: 5, z: 0})
My question is how can I apply the defaults
within the body of foo
, or somehow intercept the function before calling it and apply the defaults
public foo({x, y, z , m , n} = {x:string, y: number, z: number, m?:string, n?:number}) {
// How can I apply defaults here?
}
Just for simplicity, I have reduced the number of parameters
I am aware of the following solutions already, but I'm looking for something with less boilerplate code
public foo({x, y, z , m , n} = {x:string, y: number, z: number, m?:string, n?:number}) {
if (!m) {
m = defaults.m;
}
if (!n) {
n = defaults.n;
}
}
or
foo({...defaults, x:'x', y: 5, z: 0 });