LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
TypeScript

Functions, Optional Parameters & Overloads

Functions are the backbone of every application. In plain JavaScript, anyone can pass the wrong type of data or forget an argument, and you only find out when the app crashes in production. TypeScript solves this by letting you lock down what goes in and what comes out.

TypeScript – Functions, Optional Parameters & Overloads

Functions are the backbone of every application. In plain JavaScript, anyone can pass the wrong type of data or forget an argument, and you only find out when the app crashes in production. TypeScript solves this by letting you lock down what goes in and what comes out.

When you combine typed parameters, optional arguments, default values, and function overloads, you create APIs that are both flexible for other developers to use and 100% predictable at compile time.

What you will learn
  • How to type function parameters and return values cleanly.
  • How to use optional parameters (?) and default parameters (=) safely.
  • How function overloads work and why they beat messy union return types.
  • How TypeScript resolves overload signatures under the hood.
  • Common mistakes, hands-on practice exercises, and real interview questions.

1. Typing Function Parameters and Return Values

In TypeScript, you add types right after each parameter name using a colon. You also add the return type right after the closing parenthesis. This acts like a strict contract: if a caller breaks the contract, TypeScript immediately shows an error in your editor.

Feature Syntax Purpose
Required parameter price: number Caller must always pass this value.
Optional parameter coupon?: string Caller can skip it; value becomes undefined.
Default parameter tax: number = 0.18 Uses the fallback value if omitted or undefined.
Return type ): number Guarantees what type the function sends back.
Function overload Multiple signatures above one body Maps specific input types to exact output types.

Basic typed function

Let's write a simple function that calculates the total price of an order. Both inputs must be numbers, and the output is guaranteed to be a number.

Example 1: Typed parameters and return value

function calculateTotal(price: number, quantity: number): number {
    return price * quantity;
}

const total = calculateTotal(500, 3);
console.log("Total:", total);

Expected output

Total: 1500
Important: TypeScript can often guess (infer) the return type automatically, but writing the return type explicitly on public API functions prevents accidental bugs if someone changes the function body later.

2. Optional and Default Parameters

Real-world APIs rarely require every single argument every time. For example, a user might have a discount coupon, or they might not. TypeScript gives you two clean ways to handle this.

Using optional parameters (?)

Add a question mark (?) after the parameter name to make it optional. Inside the function, you must check if the value exists before using it.

Example 2: Optional discount parameter

function applyDiscount(price: number, discount?: number): number {
    if (discount !== undefined) {
        return price - discount;
    }
    return price;
}

console.log(applyDiscount(1000));
console.log(applyDiscount(1000, 150));

Expected output

1000
850

Using default parameters (=)

Instead of checking for undefined manually, you can assign a default value. If the caller skips the argument, TypeScript automatically uses your default.

Example 3: Default tax rate parameter

function calculateBill(amount: number, taxRate: number = 0.18): number {
    return amount + amount * taxRate;
}

console.log(calculateBill(1000));        // Uses default 0.18
console.log(calculateBill(1000, 0.05));  // Uses custom 0.05

Expected output

1180
1050
Rule to remember: Optional parameters (?) must always come after required parameters. You cannot write function test(a?: number, b: number).

3. Function Overloads for Predictable APIs

Sometimes a single function needs to accept different types of inputs and return a different type depending on what was passed in. If you only use union types (like string | number), the caller gets back a union type too, forcing them to write extra type checks.

Function overloads fix this. You write multiple overload signatures (the public rules) on top, followed by one implementation signature (the actual code) at the bottom.

Example 4: Overloaded formatValue function

// Overload signatures (visible to callers)
function formatValue(input: string): string;
function formatValue(input: number): number;

// Implementation signature (hidden from callers)
function formatValue(input: string | number): string | number {
    if (typeof input === "string") {
        return input.trim().toUpperCase();
    }
    return Math.round(input * 100) / 100;
}

const textResult = formatValue("  upgradix  "); // TypeScript knows this is string
const numResult = formatValue(99.456);          // TypeScript knows this is number

console.log(textResult);
console.log(numResult);

Expected output

UPGRADIX
99.46

Because of the overloads, textResult is strictly a string and numResult is strictly a number. You get full autocomplete for string methods on textResult without needing any extra if checks.

4. How TypeScript Resolves Function Overloads

When you call an overloaded function, TypeScript checks the overload signatures from top to bottom at compile time. Once it finds a match, it locks in the return type and runs the shared implementation body at runtime.

How TypeScript matches a function overload

Call: formatValue(99.456) Check Overload 1: (string) No match → try next Check Overload 2: (number) Matched! Return type = number Run Implementation Body → 99.46

TypeScript evaluates overload signatures in order from top to bottom. Only the single implementation function exists in the compiled JavaScript.

5. Step-by-Step Execution Breakdown

Understanding what happens at compile time versus runtime helps you avoid confusing TypeScript errors.

Step 1: You write two or more overload signatures without curly braces ({}). These define the public API.
Step 2: Directly underneath, you write one implementation signature that is broad enough to handle all the overload cases.
Step 3: Inside the implementation body, you use runtime checks like typeof or Array.isArray() to handle each case.
Step 4: When TypeScript compiles to JavaScript, all overload signatures are erased. Only the single JavaScript function remains, meaning zero runtime performance cost.
Watch out: The implementation signature is not directly callable from outside. If you have overloads for string and number, you cannot pass a variable typed as string | number unless you also add an overload for that union. Always place the most specific overloads at the top.

6. Hands-On Practice

Try these exercises in VS Code to lock in your understanding of TypeScript functions.

Beginner Exercise 1: Greeting with optional middle name

Write a function buildFullName that takes a required firstName, a required lastName, and an optional middleName. Return the formatted full name as a string.

Hint: Put middleName?: string as the third parameter so it comes after the required parameters.

Intermediate Exercise 2: Shipping calculator with default values

Create a function getShippingCost(weightKg: number, express: boolean = false): number. Standard shipping is ₹50 per kg, and express shipping adds a flat ₹150 fee.

Expected result: getShippingCost(2) returns 100, and getShippingCost(2, true) returns 250.

Advanced Exercise 3: Overloaded user lookup

Write an overloaded function findUser. If given a number (user ID), it should return a single string (username). If given a string (role), it should return a string[] (list of matching usernames).

Hint: Define two overload signatures first, then use typeof query === "number" inside the implementation.

7. Interview Questions

These are common TypeScript function questions asked in frontend and full-stack developer interviews.

Q1. What is the difference between an optional parameter (?) and a default parameter (=)?

Answer: An optional parameter (x?: number) has the type number | undefined inside the function, so you must handle undefined yourself. A default parameter (x: number = 10) automatically falls back to 10 when omitted or passed as undefined, so its type inside the function is simply number.

Q2. Can a caller invoke the implementation signature of an overloaded function directly?

Answer: No. The implementation signature is hidden from callers. TypeScript only allows calls that match one of the declared overload signatures above it.

Q3. When should you prefer union types over function overloads?

Answer: Always prefer union types when the return type does not depend on the input type (for example, accepting string | number and always returning void or boolean). Use function overloads only when the return type changes based on the exact input type or argument count.

Q4. Do function overloads add any runtime overhead in JavaScript?

Answer: No. Overload signatures exist purely for compile-time type checking. TypeScript strips them completely during compilation, leaving behind a single standard JavaScript function.

Conclusion

Well-typed functions make your codebase dramatically easier to read, refactor, and scale. Use explicit parameter and return types for clarity, optional and default parameters for convenience, and function overloads when you need strict input-to-output type mapping.

Keep your overloads simple, order them from most specific to least specific, and reach for union types whenever overloads are not strictly necessary. Your future self—and everyone consuming your API—will thank you.

Official Documentation

Upgradix by Shrash Studio – Learn Technology. Build Your Future.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.