Bird
Raised Fist0
Typescriptprogramming~15 mins

Default parameters with types in Typescript - Deep Dive

Choose your learning style10 modes available
Overview - Default parameters with types
What is it?
Default parameters with types in TypeScript allow you to give a function parameter a default value and specify the type of that parameter. This means if the caller does not provide a value, the function uses the default. It helps make functions safer and easier to use by combining type checking with fallback values.
Why it matters
Without default parameters with types, functions would require all arguments every time or risk errors from missing values or wrong types. This feature prevents bugs and makes code clearer and more reliable, especially in large projects where functions are called many times with varying inputs.
Where it fits
Before learning this, you should understand basic TypeScript types and function syntax. After this, you can explore advanced function features like rest parameters, function overloads, and generics.
Mental Model
Core Idea
A default typed parameter is like a safety net that ensures a function always has a correctly typed value to work with, even if the caller skips it.
Think of it like...
Imagine ordering coffee and the barista asks for your preferred milk type. If you don't say anything, they automatically use regular milk. The milk type is like a parameter with a default value, and specifying it clearly is like typing it to avoid surprises.
function example(param: Type = defaultValue) {
  // function body
}

┌───────────────┐
│ param: Type   │  <-- parameter with type
│ = defaultValue│  <-- default value if none given
└───────────────┘
Build-Up - 6 Steps
1
FoundationBasic function parameters in TypeScript
🤔
Concept: Functions can have parameters with specified types to ensure correct input.
function greet(name: string) { console.log(`Hello, ${name}!`); } greet('Alice'); // Works // greet(42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.
Result
The function prints 'Hello, Alice!' and TypeScript prevents wrong types at compile time.
Understanding typed parameters is the foundation for safer functions that catch errors early.
2
FoundationDefault values for function parameters
🤔
Concept: You can assign default values to parameters so the function uses them if no argument is passed.
function greet(name = 'Guest') { console.log(`Hello, ${name}!`); } greet(); // Prints 'Hello, Guest!' greet('Bob'); // Prints 'Hello, Bob!'
Result
The function works even if no argument is given, using the default 'Guest'.
Default values make functions flexible and reduce the need for callers to always provide arguments.
3
IntermediateCombining types with default parameters
🤔Before reading on: do you think TypeScript infers the type of a default parameter automatically or do you always need to specify it explicitly? Commit to your answer.
Concept: TypeScript can infer the type of a parameter from its default value, but you can also explicitly declare the type for clarity or stricter checks.
function greet(name: string = 'Guest') { console.log(`Hello, ${name}!`); } // TypeScript knows 'name' is a string because of the type annotation. function add(x = 5, y = 10) { return x + y; } // Here, TypeScript infers x and y as numbers from the default values.
Result
Functions have parameters with types either inferred or explicitly declared, combined with default values.
Knowing when TypeScript infers types versus when to specify them helps write clearer and more maintainable code.
4
IntermediateDefault parameters with complex types
🤔Before reading on: can default parameters be objects or arrays with types? Commit to your answer.
Concept: Default parameters can be complex types like objects or arrays, and you can specify their types to ensure structure and safety.
function configure(options: { verbose: boolean; debug: boolean } = { verbose: false, debug: false }) { console.log(options); } configure(); // Uses default object configure({ verbose: true, debug: false }); // Uses provided object
Result
The function safely handles missing or provided complex parameter values with type checks.
Typing complex default parameters prevents runtime errors from unexpected shapes or missing properties.
5
AdvancedInteraction with optional parameters and undefined
🤔Before reading on: does a default parameter make a parameter optional or required? Commit to your answer.
Concept: Parameters with default values are treated as optional, but their type does not include undefined unless explicitly stated.
function greet(name: string = 'Guest') { console.log(`Hello, ${name}!`); } // greet(); // OK, uses default // greet(undefined); // OK, uses default // greet(null); // Error if strict null checks are on function greetOptional(name?: string) { console.log(`Hello, ${name ?? 'Guest'}!`); } // Here, name can be undefined explicitly.
Result
Default parameters simplify optional arguments but differ subtly from optional parameters with '?' syntax.
Understanding this difference avoids confusion about when undefined is allowed and how defaults behave.
6
ExpertType widening and literal types with defaults
🤔Before reading on: does TypeScript keep a default string parameter as a literal type or widen it to string? Commit to your answer.
Concept: TypeScript widens default parameter types unless you use const assertions or explicit literal types to keep exact values.
function greet(name = 'Guest') { // name is type string, not 'Guest' } function greetLiteral(name: 'Guest' = 'Guest') { // name is type 'Guest' } const greetConst = (name = 'Guest' as const) => { // name is type 'Guest' };
Result
Default parameters can have precise literal types or widened general types depending on declaration.
Knowing how TypeScript widens types helps control function behavior and overload resolution in complex code.
Under the Hood
When a function with default parameters is called, TypeScript compiles the code to JavaScript that checks if the argument is undefined. If so, it assigns the default value. The type annotations are erased at runtime but used during compilation to check correctness. This means default values provide runtime fallback, while types provide compile-time safety.
Why designed this way?
TypeScript was designed to add static typing on top of JavaScript without changing runtime behavior. Default parameters existed in JavaScript ES6, so TypeScript leverages them and adds type checks. This design keeps compatibility and developer productivity high.
Call with args
   │
   ▼
┌─────────────────────────────┐
│ Function with default params │
│  param: Type = defaultValue │
└─────────────┬───────────────┘
              │
      Is argument undefined?
              │ Yes
              ▼
     Use defaultValue
              │ No
              ▼
     Use provided argument
              │
              ▼
   TypeScript checks type
              │
              ▼
      Run function body
Myth Busters - 3 Common Misconceptions
Quick: Does a default parameter mean the parameter type includes undefined? Commit to yes or no.
Common Belief:A parameter with a default value automatically includes undefined in its type.
Tap to reveal reality
Reality:The parameter's type does not include undefined unless explicitly declared; the default value is used only when the argument is omitted or undefined is passed.
Why it matters:Assuming undefined is part of the type can lead to unnecessary checks or incorrect assumptions about what values the function can receive.
Quick: Can you omit a parameter with a default value and still get a type error? Commit to yes or no.
Common Belief:If a parameter has a default value, you can never get a type error by omitting it.
Tap to reveal reality
Reality:You can get type errors if the default value does not match the declared type or if you pass a wrong type explicitly.
Why it matters:Ignoring this can cause runtime bugs or confusion when the function behaves unexpectedly due to type mismatches.
Quick: Does TypeScript keep the exact literal type of a default string parameter? Commit to yes or no.
Common Belief:TypeScript always keeps the exact literal type of default parameters.
Tap to reveal reality
Reality:TypeScript widens default parameter types to general types like string unless you explicitly specify literal types or use const assertions.
Why it matters:This affects function overloads and type narrowing, so misunderstanding it can cause subtle bugs.
Expert Zone
1
Default parameters are evaluated at call time, so if the default is a function call or expression, it runs each time the function is called without that argument.
2
When combining default parameters with destructured objects, you can provide defaults for nested properties, but type annotations become more complex.
3
Using default parameters affects function length property (number of expected arguments), which can impact reflection or libraries relying on function arity.
When NOT to use
Avoid default parameters when you need to distinguish between undefined and missing arguments explicitly. In such cases, use optional parameters with '?' and handle undefined inside the function. Also, avoid complex default expressions that have side effects or heavy computation.
Production Patterns
In real-world TypeScript projects, default parameters with types are used to simplify API functions, provide backward compatibility, and reduce boilerplate checks. They are combined with strict null checks and linting rules to ensure consistent and safe usage.
Connections
Optional parameters
Related concept that also deals with parameters that may be missing
Understanding default parameters clarifies how optional parameters differ in type behavior and runtime handling.
Function overloading
Builds on default parameters to create multiple function signatures with different parameter sets
Knowing default parameters helps manage overloads by providing fallback values and reducing the number of overload signatures.
Default arguments in mathematics
Similar pattern of providing fallback values when inputs are missing
Recognizing this pattern across domains shows how defaults simplify problem-solving by reducing required inputs.
Common Pitfalls
#1Assuming default parameters include undefined in their type automatically.
Wrong approach:function greet(name: string = 'Guest') { if (name === undefined) { console.log('No name'); } console.log(`Hello, ${name}!`); }
Correct approach:function greet(name: string = 'Guest') { // No need to check undefined because default handles it console.log(`Hello, ${name}!`); }
Root cause:Misunderstanding that default parameters handle undefined internally and that the type does not include undefined.
#2Passing null to a parameter with a default value expecting a string.
Wrong approach:greet(null); // Causes runtime error or unexpected output
Correct approach:greet(); // Uses default 'Guest' greet('Alice'); // Uses provided string
Root cause:Confusing null with undefined; default parameters only replace undefined, not null.
#3Using complex expressions with side effects as default values without realizing they run every call.
Wrong approach:function logTime(time = Date.now()) { console.log(time); } logTime(); logTime();
Correct approach:const fixedTime = Date.now(); function logTime(time = fixedTime) { console.log(time); } logTime(); logTime();
Root cause:Not realizing default values are evaluated at each call, causing unexpected repeated side effects.
Key Takeaways
Default parameters with types combine fallback values and type safety to make functions easier and safer to use.
TypeScript can infer parameter types from default values but explicit types improve clarity and prevent errors.
Default parameters are treated as optional but differ from optional parameters in how undefined is handled.
Understanding type widening with default parameters helps control function behavior and avoid subtle bugs.
Default values are evaluated at call time, so avoid heavy or side-effect expressions as defaults.

Practice

(1/5)
1.

What is the main purpose of default parameters in TypeScript functions?

easy
A. To provide fallback values when arguments are missing
B. To enforce strict typing on function return values
C. To declare variables inside functions
D. To create anonymous functions

Solution

  1. Step 1: Understand default parameters

    Default parameters give a value to a function argument if no value is passed.
  2. Step 2: Identify the purpose

    This helps avoid errors when arguments are missing by providing fallback values.
  3. Final Answer:

    To provide fallback values when arguments are missing -> Option A
  4. Quick Check:

    Default parameters = fallback values [OK]
Hint: Default parameters fill missing arguments automatically [OK]
Common Mistakes:
  • Confusing default parameters with return type enforcement
  • Thinking default parameters declare variables
  • Mixing default parameters with anonymous functions
2.

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; }
easy
A. function multiply(x: number, y = 2: number) { return x * y; }
B. function multiply(x = 2: number, y: number) { return x * y; }
C. function multiply(x: number, y: number = 2) { return x * y; }
D. function multiply(x:, y: number = 2) { return x * y; }

Solution

  1. Step 1: Check parameter type and default value syntax

    In TypeScript, the type annotation comes before the default value: param: type = default.
  2. Step 2: Verify each option

    function multiply(x: number, y: number = 2) { return x * y; } correctly uses y: number = 2. Others have syntax errors or wrong order.
  3. Final Answer:

    function multiply(x: number, y: number = 2) { return x * y; } -> Option C
  4. Quick Check:

    Type before default value = correct syntax [OK]
Hint: Type annotation before default value: param: type = value [OK]
Common Mistakes:
  • Placing default value before type annotation
  • Omitting type annotation on default parameter
  • Assigning default to wrong parameter
3.

What is the output of the following TypeScript code?

function greet(name: string = "Guest") {
  return `Hello, ${name}!`;
}

console.log(greet());
console.log(greet("Alice"));
medium
A. Hello, undefined!\nHello, Alice!
B. Hello, Guest!\nHello, Alice!
C. Hello, !\nHello, Alice!
D. Error: Missing argument for name

Solution

  1. Step 1: Analyze default parameter usage

    Calling greet() without argument uses default "Guest".
  2. Step 2: Check outputs for both calls

    First call prints "Hello, Guest!"; second call prints "Hello, Alice!".
  3. Final Answer:

    Hello, Guest!\nHello, Alice! -> Option B
  4. Quick Check:

    Default parameter used when argument missing [OK]
Hint: Default parameter fills missing argument in function call [OK]
Common Mistakes:
  • Expecting undefined instead of default value
  • Thinking missing argument causes error
  • Ignoring template literal output format
4.

Identify the error in this TypeScript function and choose the correct fix:

function calculateArea(width: number = 5, height: number) {
  return width * height;
}
medium
A. Move the parameter with default value to the end: function calculateArea(height: number, width: number = 5) {...}
B. Remove the default value from width: function calculateArea(width: number, height: number) {...}
C. Add a default value to height: function calculateArea(width: number = 5, height: number = 10) {...}
D. No error; function is correct as is

Solution

  1. Step 1: Understand parameter order rules

    In TypeScript, parameters with default values must come after parameters without defaults.
  2. Step 2: Fix parameter order

    Moving width with default to the end fixes the error.
  3. Final Answer:

    Move the parameter with default value to the end: function calculateArea(height: number, width: number = 5) {...} -> Option A
  4. Quick Check:

    Default parameters must be last [OK]
Hint: Put default parameters after required ones [OK]
Common Mistakes:
  • Placing default parameters before required ones
  • Ignoring TypeScript parameter order rules
  • Assuming no error when order is wrong
5.

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?

hard
A. Error due to conflicting default parameters
B. { verbose: true }\n{ verbose: true }
C. { verbose: true }\n{ verbose: false }
D. { verbose: false }\n{ verbose: true }

Solution

  1. Step 1: Understand default parameter values

    Both options and defaults have default objects with verbose flags.
  2. Step 2: Analyze object merging

    Using spread, { ...defaults, ...options } merges with options overriding defaults.
  3. Step 3: Evaluate calls

    First call uses defaults: options = { verbose: false }, defaults = { verbose: true }, merged result is { verbose: false } because options overwrites defaults.
  4. Step 4: Check second call

    Second call passes { verbose: true } as options, so merged result is { verbose: true }.
  5. Final Answer:

    { verbose: false }\n{ verbose: true } -> Option D
  6. Quick Check:

    Options override defaults in merge [OK]
Hint: Spread merges with later objects overriding earlier ones [OK]
Common Mistakes:
  • Confusing which object overrides which in spread
  • Assuming default parameters merge automatically
  • Ignoring optional property in type
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard