0
0
Typescriptprogramming~5 mins

Default parameters with types in Typescript

Choose your learning style9 modes available
Introduction

Default parameters let you give a value to a function input if no value is provided. Adding types helps catch mistakes early.

When you want a function to work even if some inputs are missing.
When you want to avoid errors from undefined inputs.
When you want to make your code easier to understand by showing expected input types.
When you want to provide common default values for function inputs.
When you want to keep your functions flexible and safe.
Syntax
Typescript
function functionName(paramName: type = defaultValue) {
  // function body
}

The default value is used only if the caller does not provide that argument.

TypeScript checks that the default value matches the declared type.

Examples
This function greets someone. If no name is given, it says "friend".
Typescript
function greet(name: string = "friend") {
  console.log(`Hello, ${name}!`);
}
This function multiplies two numbers. If the second number is missing, it uses 2.
Typescript
function multiply(x: number, y: number = 2): number {
  return x * y;
}
This function prints a flag value. It defaults to true if no value is passed.
Typescript
function setFlag(flag: boolean = true) {
  console.log(`Flag is ${flag}`);
}
Sample Program

This program shows how default parameters work with types. It prints details about a person. If no name or age is given, it uses default values.

Typescript
function describePerson(name: string = "Unknown", age: number = 0) {
  console.log(`Name: ${name}, Age: ${age}`);
}

describePerson();
describePerson("Alice");
describePerson("Bob", 30);
OutputSuccess
Important Notes

Default parameters must come after required parameters in the function signature.

You can use any valid expression as a default value, not just constants.

Summary

Default parameters provide fallback values when arguments are missing.

Type annotations ensure the default value matches the expected type.

This makes functions safer and easier to use.