To declare a parameter of a function as optional in TypeScript, we need to add ?
after the parameter name. For example, if a parameter name is id
and we want it to be optional then we need to write it as id?
.
Let’s understand it better by declaring a simple greet
function that takes an argument message
and logs it.
function greet(message: string) {
console.log(message);
}
greet("Hello"); // Hello
Here, we need to pass message
of type string or Typescript will complain about it.
function greet(message: string) {
console.log(message);
}
greet(); // Expected 1 arguments, but got 0. An argument for 'message' was not provided.
TypeScript will throw an error, Expected 1 arguments, but got 0. An argument for 'message' was not provided.
If we want to make message
an optional parameter, we can rename it to message?
function greet(message?: string) {
if (message) {
console.log(message);
} else {
console.log("Hi");
}
}
greet("Hello"); // Hello
greet(); // Hi
In the above example, message
is now an optional parameter. Even if we do not pass an argument in greet()
function, TypeScript will not complain. If the message
is present we will see the message
getting printed else the text Hi
will be displayed.