define default values for function parameters in typescript

In TypeScript, you can set default parameter values for a function by providing a default value for each parameter. To do this, you add an equals sign (=) followed by the default value after the parameter declaration. For example:

index.ts
function greet(name: string = 'World') {
  console.log(`Hello, ${name}!`);
}

greet(); // Output: Hello, World!
greet('John'); // Output: Hello, John!
151 chars
7 lines

In the example above, the greet function takes a parameter name which has a default value of 'World'. This means that if the name parameter is not provided when the greet function is called, the default value 'World' will be used.

You can also combine default parameters with optional parameters, like this:

index.ts
function greet(name?: string, greeting: string = 'Hello') {
  console.log(`${greeting}, ${name || 'World'}!`);
}

greet(); // Output: Hello, World!
greet('John'); // Output: Hello, John!
greet('Jane', 'Hi'); // Output: Hi, Jane!
229 chars
8 lines

In the example above, the greet function takes two parameters, name and greeting. The name parameter is optional, indicated by the ? after the parameter name. The greeting parameter has a default value of 'Hello'. If name is not provided, the string 'World' is used instead. If greeting is not provided, the default value 'Hello' is used.

With default parameters, you can reduce the boilerplate code required to check for the existence of a parameter and provide a default value if it doesn't exist.

gistlibby LogSnag