I have an object that has a constructor with an optional parameter like this:
class example{
constructor(a: string,b: string,c: string,d?:string){
//...
}
}
This class will be instatiated inside another method. Like this:
function createExample(a: string,b: string,c: string,d?:string){
return new example(a,b,c,d)
}
But i only want to pass the "d" parameter if the function createExample() received. Is there a way in javascript/typescript to do this. Something like:
I want to pass the parameter d only if it exists, and I hope I don't have to do an if that checks this, because if I have more optional parameters it can get complicated. Is there a way in javascript/typescript to do this. Something like:
function createExample(a: string,b: string,c: string,d?:string){
return new example(a,b,c,d?)
}
Or should I just leave the instatiaton with the normal "d" parameter, and in case it is not defined, it should be passed as undefined?
CodePudding user response:
If you define the type for D
as potentially undefined, you can just pass it in
class Example {
constructor(a: string, b: string, c: string, d?: string) {
// ...
}
}
const A = "";
const B = "";
const C = "";
let D: string | undefined;
if (someCondition) {
D = "d";
}
const ex = new Example(A, B, C, D);
CodePudding user response:
Or should I just leave the instatiaton with the normal "d" parameter, and in case it is not defined, it should be passed as undefined?
Yes, exactly this. JavaScript treats missing arguments and undefined
being passed as an argument the same1 - both end up with an undefined
or defaulted parameter. So it's as simple as
function createExample(a: string, b: string, c: string, d?: string) {
return new Example(a, b, c, d);
}
If you really care, you can use spread syntax with an array:
function createExample(...args: [a: string, b: string, c: string, d?: string]) {
return new Example(...args);
}
1: except for arguments.length
and rest parameter syntax