How To Omit One Optional Parameter While Providing Another In TypeScript

Omit one optional parameter while providing another in TS

It is expected if you define some function that requires passing an argument. I will help you find out how to omit one optional parameter while providing another in TS. Let’s go into detail.

Omit one optional parameter while providing another in TS

If you do it in a normal way, it will get an error.

Example:

function logInfor(name:string , age:number ,country:string ){
  console.log(name)
  console.log(age)
­ console.log(country)
}
logInfor('Togban', “VietNam”)
 

Error:

Expected 3 arguments, but got 2.ts(2554)
test.ts(1, 45): An argument for 'age' was not provided.

Solution 1: Pass in undefined

To use this solution, your parameters have to be set to an optional type.

Example:

function logInfor(name:string , age?:number ,country:string ) {
  console.log(name)
  console.log(age)
  console.log(country)
}
logInfor('Togban', undefined,'VietNam')

Output:

[LOG]: "Togban"
[LOG]: undefined
[LOG]: "VietNam"

If you pass an ‘undefined’ value, it is also like you don’t pass the value. If you don’t pass any value to parameters, those parameters will be assigned an ‘undefined’ value.

If you want to omit all values in the parameter, you will have to set an optional type for all parameters.

Example:

function logInfor(name?:string , age?:number ,country?:string ) {
  console.log(name)
  console.log(age)
  console.log(country)
}
logInfor(undefined, undefined,undefined)

Output:

[LOG]: undefined
[LOG]: undefined
[LOG]: undefined 

But it would be best if you used it this way when there is no required parameter.

Solution 2: Set the default value

You can also do it by set implicitly typing for your parameters by setting the default value.

Example:

function logInfor(name:string , age:number=18 ,country:string ) {
  console.log(name)
  console.log(age)
  console.log(country)
}
logInfor('Togban', undefined,'VietNam')

Output :

[LOG]: "Togban"
[LOG]: 18
[LOG]: "VietNam"

Here value “18” has been set to age parameters, so it will take value “18” if its value is “undefined” or “null”. But of course, we only set the default value for age parameters, not another, so only age parameters are optional, not name or country, so both of their value is still required.

Example:

function logInfor(name:string , age:number=18 ,country:string ) {
  console.log(name)
  console.log(age)
  console.log(country)
}
logInfor('Togban',undefined,undefined)

Error:

· Argument of type 'undefined' is not assignable to parameter of type 'string'.

Summary

In this tutorial, I explained how to omit one optional parameter while providing another in TS. You can replace it by passing in undefined but ensure that you set parameters to optional type. And you can set a value with a default value if it is a loop value.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *