What if your functions could handle missing inputs all by themselves, without extra code?
Why Default parameters with types in Typescript? - Purpose & Use Cases
Imagine you are writing a function that greets users. You want to say "Hello" to a user, but if no name is given, you want to say "Hello, Guest". Without default parameters, you have to write extra code to check if the name was provided every time.
This manual way is slow and error-prone because you must always remember to check if the input exists. If you forget, your program might crash or behave unexpectedly. It also makes your code longer and harder to read.
Default parameters with types let you set a default value right in the function signature. This means if no value is passed, the default is used automatically. It keeps your code clean, safe, and easy to understand.
function greet(name: string | undefined) {
if (name === undefined) {
name = "Guest";
}
console.log(`Hello, ${name}`);
}function greet(name: string = "Guest") {
console.log(`Hello, ${name}`);
}This makes your functions simpler and safer, so you can focus on what your program should do instead of checking inputs all the time.
When building a website, you might have a function to show user profiles. If the user doesn't provide a profile picture, you can use a default image automatically using default parameters with types.
Default parameters save you from writing extra checks.
They make your code cleaner and easier to read.
Typing default parameters helps catch errors early.
Practice
What is the main purpose of default parameters in TypeScript functions?
Solution
Step 1: Understand default parameters
Default parameters give a value to a function argument if no value is passed.Step 2: Identify the purpose
This helps avoid errors when arguments are missing by providing fallback values.Final Answer:
To provide fallback values when arguments are missing -> Option AQuick Check:
Default parameters = fallback values [OK]
- Confusing default parameters with return type enforcement
- Thinking default parameters declare variables
- Mixing default parameters with anonymous functions
Which of the following is the correct syntax for a TypeScript function with a default parameter of type number?
function multiply(x: number, y: number = 2) { return x * y; }Solution
Step 1: Check parameter type and default value syntax
In TypeScript, the type annotation comes before the default value:param: type = default.Step 2: Verify each option
function multiply(x: number, y: number = 2) { return x * y; } correctly usesy: number = 2. Others have syntax errors or wrong order.Final Answer:
function multiply(x: number, y: number = 2) { return x * y; } -> Option CQuick Check:
Type before default value = correct syntax [OK]
- Placing default value before type annotation
- Omitting type annotation on default parameter
- Assigning default to wrong parameter
What is the output of the following TypeScript code?
function greet(name: string = "Guest") {
return `Hello, ${name}!`;
}
console.log(greet());
console.log(greet("Alice"));Solution
Step 1: Analyze default parameter usage
Callinggreet()without argument uses default"Guest".Step 2: Check outputs for both calls
First call prints "Hello, Guest!"; second call prints "Hello, Alice!".Final Answer:
Hello, Guest!\nHello, Alice! -> Option BQuick Check:
Default parameter used when argument missing [OK]
- Expecting undefined instead of default value
- Thinking missing argument causes error
- Ignoring template literal output format
Identify the error in this TypeScript function and choose the correct fix:
function calculateArea(width: number = 5, height: number) {
return width * height;
}Solution
Step 1: Understand parameter order rules
In TypeScript, parameters with default values must come after parameters without defaults.Step 2: Fix parameter order
Movingwidthwith default to the end fixes the error.Final Answer:
Move the parameter with default value to the end: function calculateArea(height: number, width: number = 5) {...} -> Option AQuick Check:
Default parameters must be last [OK]
- Placing default parameters before required ones
- Ignoring TypeScript parameter order rules
- Assuming no error when order is wrong
Consider this function that merges two objects with default parameters:
function mergeOptions(options: { verbose?: boolean } = { verbose: false }, defaults: { verbose: boolean } = { verbose: true }) {
return { ...defaults, ...options };
}
console.log(mergeOptions());
console.log(mergeOptions({ verbose: true }));What is the output of the two console.log calls?
Solution
Step 1: Understand default parameter values
Bothoptionsanddefaultshave default objects with verbose flags.Step 2: Analyze object merging
Using spread,{ ...defaults, ...options }merges withoptionsoverridingdefaults.Step 3: Evaluate calls
First call uses defaults:options = { verbose: false },defaults = { verbose: true }, merged result is{ verbose: false }becauseoptionsoverwritesdefaults.Step 4: Check second call
Second call passes{ verbose: true }asoptions, so merged result is{ verbose: true }.Final Answer:
{ verbose: false }\n{ verbose: true } -> Option DQuick Check:
Options override defaults in merge [OK]
- Confusing which object overrides which in spread
- Assuming default parameters merge automatically
- Ignoring optional property in type
Ready to prove it?
Pass the test and this pattern moves unknown
