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.
- 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
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
?) 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
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.
{}). These define the public API.typeof or Array.isArray() to handle each case.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.
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.
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.
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.
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.
Answer: No. The implementation signature is hidden from callers. TypeScript only allows calls that match one of the declared overload signatures above it.
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.
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.