Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
Is there a way in typescript to pass an optional parameter to a constructor only if it exist?

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!