Typescript optional function parameter

How to use TypeScript optional parameters with example code

TypeScript is a superset of JavaScript that has climbed up in popularity in the past few years. In this post, we will learn how to use optional parameters in TypeScript functions, let’s get started!

TypeScript optional parameters with example code

Table of contents #

Example of printing full name #

For this tutorial we will use a simple yet useful example of getting the full name, the rules are:

  • If the middle name is provided full name has the middle name included
  • In case the name has only first and last name the full name will not have the middle name included.

It can be coded as below in both JavaScript and TypeScirpt as we will see in the next section as well as how optional parameters make it easy to get the desired output minimizing errors in TypeScript.

Optional parameters in JavaScirpt #

By default, all the parameters in JavaScript are optional. Let’s look at this with above mentioned example of getting the fullname with first name, middle name and last name below:

function getFullName(firstName, lastName, middleName)  
const fullName = middleName ? `$firstName> $middleName> $lastName>` : `$firstName> $lastName>`;

return fullName;
>

console.log(getFullName());
console.log(getFullName('John'));
console.log(getFullName('John', 'Doe'));
console.log(getFullName('John', 'Doe', 'MiddleName'));

The above code will give the output as follows:

undefined undefined
John undefined
John Doe
John MiddleName Doe

So in ES6 Javascript, there isn’t a way to make a function parameter required, this is how JavaScript works as it is a bit too flexible. That is a reason why we can use TypeScript to add types as well as make the function parameters required, let’s look at the same example with TypeScript. We can use nodemon to compile and execute the script on save. We can also use docker with Node.js to deploy the compiled code easily.

Optional parameters with TypeScript #

For the same example we wil now use TypeScript and write the getFullName function as below in the optional-params.ts file, notice the file is .ts for typescript:

function getFullName(firstName: string, lastName: string, middleName?: string)  
const fullName = middleName ? `$firstName> $middleName> $lastName>` : `$firstName> $lastName>`;
return fullName;
>

//console.log(getFullName('John')); // compile error - An argument for 'lastName' was not provided.
console.log(getFullName('John', 'Doe'));
console.log(getFullName('John', 'Doe', 'MiddleName'));

The ? after the middle name indicates the TS compiler it is an optional parameter.

We will also need to create a tsconfig.json file with the following contents:

 
"compilerOptions":
"target": "es5",
"module": "commonjs",
"sourceMap": true
>
>

We will use tsc and node to run the above TypeScript file after compiling it to JavaScript with the following command:

tsc optional-params.ts && node optional-params.js

Given we have Node installed, we can get the TypeScript compiler with npm install -g typescript . The above command will first compile the TypeScript file called optional-params.ts to Javascript and the second command will execute the Javascript as a Node.js script. It will give us the following output:

John Doe
John MiddleName Doe

Let us quickly go through what the above script does:

  1. The getFullName function takes 3 parameters, firstName , lastName and middleName where only middleName is optional.
  2. If there is middleName is passed the function will print the full name with the middle name else it will only be first name and last name.
  3. Line 6 if uncommented will stop the compilation process with the error An argument for ‘lastName’ was not provided. as the last name is a required parameter by default.
  4. Line 7 and 8 will work where the first valid call will log John Doe without a middle name and the second call will log John MiddleName Doe with the optional parameter of the middle name passed.

You can try the above code in the TypeScript playground and fiddle around with it or use this one.

Default params in Typescript #

The above typescript code can be simplified with use of default params, for instance if the middleName can be set to »- empty string if not provided the above code can be written as:

function getFullName(firstName: string, lastName: string, middleName: string = '')  
const fullName = `$firstName> $middleName> $lastName>`;
return fullName;
>

//console.log(getFullName('John')); // compile error - An argument for 'lastName' was not provided.
console.log(getFullName('John', 'Doe'));
console.log(getFullName('John', 'Doe', 'MiddleName'));

The above function looks pretty similar the main difference is, that the middleName is set as a default value of an empty string if not provided. This has a similar output as seen below:

John Doe
John MiddleName Doe

There is a couple of extra spaces when only the first name and last name are printed but that is a tradeoff we can take for the simplified code. All the code is available as part of this pull request for your reference.

Conclusion #

In this useful guide, we saw how to use optional parameters in the TypeScript function with a simple yet practical example.

I hope it has helped you unravel how optional and default parameters work in TypeScript.

Geshan Manandhar | 12-Jun-2022

Источник

TypeScript Optional Parameters

Summary: in this tutorial, you will learn how to use the TypeScript optional parameters for functions.

In JavaScript, you can call a function without passing any arguments even though the function specifies parameters. Therefore, JaveScript supports the optional parameters by default.

In TypeScript, the compiler checks every function call and issues an error in the following cases:

  • The number of arguments is different from the number of parameters specified in the function.
  • Or the types of arguments are not compatible with the types of function parameters.

Because the compiler thoroughly checks the passing arguments, you need to annotate optional parameters to instruct the compiler not to issue an error when you omit the arguments.

To make a function parameter optional, you use the ? after the parameter name. For example:

function multiply(a: number, b: number, c?: number): number < if (typeof c !== 'undefined') < return a * b * c; > return a * b; >Code language: JavaScript (javascript)
  • First, use the ? after the c parameter.
  • Second, check if the argument is passed to the function by using the expression typeof c !== ‘undefined’ .

Note that if you use the expression if(c) to check if an argument is not initialized, you would find that the empty string or zero would be treated as undefined .

The optional parameters must appear after the required parameters in the parameter list.

For example, if you make the b parameter optional, and c parameter required the TypeScript compiler will issue an error:

function multiply(a: number, b?: number, c: number): number < if (typeof c !== 'undefined') < return a * b * c; > return a * b; >Code language: JavaScript (javascript)
error TS1016: A required parameter cannot follow an optional parameter.

Summary

  • Use the parameter?: type syntax to make a parameter optional.
  • Use the expression typeof(parameter) !== ‘undefined’ to check if the parameter has been initialized.

Источник

How Do Optional Parameters Work In TypeScript?

Tim Mouskhelichvili

As you may know, TypeScript is a strongly typed language. By default, when you declare a function with parameters, you need to pass values for each parameter when you call it. Sometimes, however, developers may want to make a function parameter non-required. Luckily, TypeScript offers optional parameters to fix this issue.

In TypeScript, to create a function with an optional parameter, you need to use a question mark after the parameter declaration, like so:

typescriptconst getFullName = (firstName: string, lastName?: string): string => < if (!lastName) < return firstName; > return `$ $ `; >

This article will go through everything about optional parameters in TypeScript and answer common questions.

Optional parameters in TypeScript

In TypeScript, when you call a function with parameters, the compiler checks that you pass the correct number of arguments and the right argument types.

TypeScript considers all the parameters required unless specified otherwise.

To define an optional parameter, you must use a question mark ( ? ) after a parameter name.

Here is an example of a function with an optional parameter:

typescriptconst getError = (message: string, error?: number): string => < if (!error) < return message; > return `$ : $ `; >

Note: Here we are using string interpolation to concat the strings.

In this example, the error parameter is optional.

You can also define multiple optional parameters, like so:

typescriptconst getAddress = (code: string, address?: string, city?: string): string => < return `$ | $''> | $''>`; >;

Note: Use default parameters if you want to provide a default value for a parameter.

Order of optional parameters

When you have optional parameters in a function, it is essential to follow the correct order.

Optional parameters should always be placed AFTER the required parameters.

Otherwise, the TypeScript compiler will complain.

How to check if a value was passed to an optional parameter?

The parameter is undefined when a developer doesn’t pass a value to an optional parameter.

To check if an optional parameter has no value, simply check if the parameter’s type is undefined , like so:

typescriptconst getAddress = (code: string, address?: string): string => < if (typeof address === 'undefined') < return code; > return `$ | $ `; >;

In this example, we check that the address parameter has no value with an if statement.

The best Web Development course in 2023! 👉 Learn Web Development

How to define an optional parameter in an interface?

In TypeScript, you can also define interface optional properties.

Here is an example of how to do it:

typescriptinterface IAddress < city: string; address: string; street?: string; >

In this example, the city and address fields are required, and the street property is optional.

How to define an optional parameter in a constructor?

You can also define an optional parameter in a class constructor.

Here is an example of an optional parameter in a constructor:

typescriptclass Animal < public constructor( public name: string, public age?: number ) <>; >

In this example, the age constructor parameter is optional.

Final thoughts

As you can see, setting up optional parameters in TypeScript is easy.

You can set an optional parameter in functions, interfaces, types, and constructors.

With functions, place all the optional parameters after the required ones.

typescript optional parameters

Here are other TypeScript tutorials for you to enjoy:

The best Web Development course in 2023! 👉 Learn Web Development

Tim Mouskhelichvili

Hello! I am Tim Mouskhelichvili, a Freelance Developer & Consultant from Montreal, Canada. I specialize in React, Node.js & TypeScript application development. If you need help on a project, please reach out, and let’s work together.

Источник

Читайте также:  Html coding with php
Оцените статью