Functions in TypeScript
TypeScript functions are the workhorses of your code. You can type their parameters, return values, and even the shape of callbacks they accept. This makes function calls safer because the compiler checks every argument before the code runs. In real projects, well-typed functions prevent bugs and act as living documentation.
This tutorial covers typing parameters and return values, optional and default parameters, rest parameters, arrow functions and function type expressions, void returns, callback types, function overloads, and the this parameter. You will also see the common mistake of placing an optional parameter before a required one.
What Are TypeScript Functions?
A TypeScript function is a reusable block of code that accepts typed inputs and returns a typed output. You annotate each parameter with its type and optionally annotate the return type. The compiler then checks every call against that contract.
Here is a simple example:
function add(a: number, b: number): number {
return a + b;
}
console.log(add(3, 4));
// Output: 7
Both parameters must be numbers, and the return value is a number. Passing a string would fail at compile time.
How Do You Type Parameters and Return Values?
Every parameter gets a type after its name. The return type goes after the closing parenthesis, before the opening brace. Under "strict": true, untyped parameters are an error because noImplicitAny is on.
function greet(name: string, age: number): string {
return `${name} is ${age} years old.`;
}
console.log(greet("Riya", 28));
// Output: Riya is 28 years old.
// greet("Riya", "28");
// Error: Argument of type 'string' is not assignable to parameter of type 'number'.
How it works: The compiler checks the types of both arguments at the call site. "Riya" matches string, and 28 matches number. The return type : string is also checked against the return statement. If you omit the return annotation, TypeScript infers it from the returned expression, which is fine for simple functions.
How Do Optional and Default Parameters Work?
An optional parameter uses ? after its name and may be omitted by the caller. A default parameter uses = to provide a value when the argument is missing. Optional parameters must come after required ones.
function createUser(name: string, role = "viewer", nickname?: string): string {
const nick = nickname ?? "none";
return `${name} (${role}) nickname: ${nick}`;
}
console.log(createUser("Arjun"));
console.log(createUser("Sana", "admin"));
console.log(createUser("Meera", "editor", "mee"));
// Output: Arjun (viewer) nickname: none
// Output: Sana (admin) nickname: none
// Output: Meera (editor) nickname: mee
How it works: role has a default of "viewer", so it is optional at the call site. nickname is optional with no default, so its type is string | undefined. The ?? operator provides a fallback. If you tried to place nickname? before role = "viewer", that would be fine because both are optional, but a required parameter after an optional one is a compile error, covered later.
How Do Rest Parameters Work?
A rest parameter collects any number of trailing arguments into an array. You write it with ... before the name and annotate it as an array type. There can be only one rest parameter, and it must be last.
function sum(...values: number[]): number {
return values.reduce((total, value) => total + value, 0);
}
console.log(sum(1, 2, 3));
console.log(sum(10, 20, 30, 40));
// Output: 6
// Output: 100
How it works: The ...values: number[] collects all arguments into a number[]. Inside the function, values is a normal array, so reduce works as usual. The compiler checks that every argument passed is a number. A rest parameter is a clean way to accept a variable number of inputs.
How Do Arrow Functions and Function Type Expressions Work?
An arrow function is a shorter function syntax that uses =>. A function type expression describes the shape of a function as a type, listing parameter types and the return type. Together they let you pass functions around with full type safety.
type Operation = (a: number, b: number) => number;
const multiply: Operation = (a, b) => a * b;
console.log(multiply(6, 7));
// Output: 42
How it works: The Operation type says "a function that takes two numbers and returns a number." The arrow function assigned to multiply gets its parameter types from the type annotation through contextual typing, so a and b are numbers without being annotated again. If the function returned a string, the assignment would fail.
What Does a void Return Type Mean?
A void return type means the function does not return a useful value. It may return undefined, but callers should not rely on the result. This is common for logging, event handlers, and side-effect functions.
function logMessage(message: string): void {
console.log(`[LOG] ${message}`);
}
logMessage("Started");
// Output: [LOG] Started
How it works: The function performs an action and returns nothing. The void annotation tells callers not to use the return value. Under strict mode, you cannot assign the result of a void function to a variable of a useful type. This connects to the difference between void and never from the TypeScript Any, Unknown & Never tutorial: void returns normally, never never returns.
How Do You Type Callback Parameters?
A callback is a function passed to another function to be called later. You type it with a function type expression, either inline or as a named alias. The compiler then checks that the callback's parameters and return match.
function processItems(items: string[], callback: (item: string, index: number) => void): void {
items.forEach((item, index) => callback(item, index));
}
processItems(["pen", "book"], (item, index) => {
console.log(`${index}: ${item}`);
});
// Output:
// 0: pen
// 1: book
How it works: The callback parameter is typed as (item: string, index: number) => void. When you pass the arrow function, TypeScript infers item as a string and index as a number through contextual typing. If you tried to call callback with a number for item, the compiler would reject it inside processItems. This pattern is everywhere in array methods, event handlers, and async code.
How Do Function Overloads Work?
A function overload lets one function accept different argument shapes and return different types based on the shape. You write several signatures followed by one implementation. The compiler picks the matching signature at the call site.
function format(value: string): string;
function format(value: number): string;
function format(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(2);
}
console.log(format("hello"));
console.log(format(3.14159));
// Output: HELLO
// Output: 3.14
How it works: The two signature lines declare the allowed call shapes. The implementation signature is wider; it accepts string | number and must handle both. Callers only see the two public signatures, so format(true) would be a compile error even though the implementation would technically run. Overloads are useful when a single function returns different types depending on input, such as a parser or a formatter.
What Is the this Parameter?
The this parameter is a special first parameter that tells TypeScript what this refers to inside a function. It does not count as a real argument at runtime, so callers do not pass it. It helps when you pass methods around as callbacks.
type Counter = { count: number };
function increment(this: Counter, by: number): void {
this.count += by;
}
const counter: Counter = { count: 0 };
increment.call(counter, 5);
console.log(counter.count);
// Output: 5
How it works: The this: Counter parameter tells TypeScript that inside increment, this has a count property. Calling increment.call(counter, 5) binds this to the counter object. If you tried to call increment(5) directly, the compiler would warn that this is not bound. This is a small feature, but it matters when passing object methods as callbacks.
Common Mistakes and Best Practices
- Putting an optional parameter before a required one. TypeScript rejects
function f(a?: number, b: string). The caller cannot tell which argument maps to which. Put required parameters first and optional ones last. - Annotating callback parameters twice. If the callback type is already declared, let contextual typing handle the parameters. Writing
(item: string) => ...inside a call that already knows the type is noise. - Forgetting the implementation signature in overloads. Overload signatures must be followed by exactly one implementation that is compatible with all of them. Missing it produces a confusing error.
- Using
voidfor functions that actually return a value. If the function returns a value and callers use it, type it as the real return type.voidhides that information and makes the function harder to compose. - Writing
functionwhen an arrow function is clearer for callbacks. Arrow functions do not bind their ownthis, so they are safer as callbacks. Use them for short inline functions and keep named functions for top-level logic.
Real-World Example: A Price Calculator and a Formatter
This example combines optional, default, and rest parameters in a calculator, plus a two-signature overload for formatting.
type Currency = "INR" | "USD";
function calculate(
base: number,
taxRate = 0.18,
...discounts: number[]
): number {
const discountTotal = discounts.reduce((sum, d) => sum + d, 0);
const afterDiscount = base - discountTotal;
return afterDiscount + afterDiscount * taxRate;
}
function format(value: string): string;
function format(value: number, currency?: Currency): string;
function format(value: string | number, currency: Currency = "INR"): string {
if (typeof value === "string") {
return value.trim().toUpperCase();
}
const symbol = currency === "INR" ? "Rs" : "$";
return `${symbol} ${value.toFixed(2)}`;
}
console.log(calculate(1000, 0.18, 100, 50).toFixed(2));
console.log(format(" hello "));
console.log(format(499.5));
console.log(format(20, "USD"));
// Output: 1003.00
// Output: HELLO
// Output: Rs 499.50
// Output: $ 20.00
How it works, line by line. The calculate function takes a required base, a default taxRate = 0.18, and rest discounts: number[]. It sums the discounts, subtracts them from the base, then adds tax. The result of calculate(1000, 0.18, 100, 50) is (1000 - 150) * 1.18 = 1003. The format function has two overload signatures: one for strings and one for numbers with an optional currency. The implementation accepts string | number and branches on typeof value. For strings, it trims and upper-cases. For numbers, it picks the symbol and formats to two decimals. The default currency = "INR" makes the second argument optional in the number signature. Each call matches the right signature, and TypeScript checks the return type is a string in every case.
Summary
- TypeScript functions let you type parameters, return values, and callbacks for safety at call sites.
- Optional parameters use
?; default parameters use=; rest parameters use...and must come last. - Arrow functions and function type expressions describe callback shapes cleanly.
voidmeans the function returns no useful value but returns normally.- Function overloads let one function accept several call shapes with different returns.
- The
thisparameter typesthisinside methods that are passed as callbacks.
Now that you can type functions precisely, continue to the Classes in TypeScript tutorial to learn how to build typed objects with methods, constructors, and inheritance.
Frequently Asked Questions
Why can I not put an optional parameter before a required one?
Because the caller would not know which argument maps to which parameter. If a is optional and b is required, calling f(undefined, "x") is confusing. TypeScript requires optional parameters to come after all required ones so the argument order stays predictable.
Do I need to write the return type on every function?
No. TypeScript infers the return type from the returned expression. For short internal functions, inference is fine. For exported functions or public APIs, write the return type explicitly so a future edit to the body cannot silently change the contract.
What is the difference between void and undefined as a return type?
void says the function does not return a useful value, and callers should not use the result. undefined is an actual value and a real type. If you write : undefined, the caller can still store it and compare it. Use void for side-effect functions and undefined only when undefined is a meaningful return value.
How many overload signatures can a function have?
There is no hard limit. You can write as many overload signatures as you need, followed by exactly one implementation signature. Keep the list short, usually two or three, so the function stays easy to understand. If you need many overloads, consider a discriminated union or a generic instead.
Practice Exercises
Exercise 1 (Easy): Type Parameters and Return
Write a function area(width: number, height: number): number that returns the area. Call it with two numbers and print the result.
Show solution
function area(width: number, height: number): number {
return width * height;
}
console.log(area(5, 8));
// Output: 40
Both parameters are typed as numbers and the return type is number, so the call is checked at compile time.
Exercise 2 (Easy): Optional and Default Parameters
Write a function makeCard(title: string, subtitle = "none", footer?: string): string that returns a formatted string. Call it with one, two, and three arguments.
Show solution
function makeCard(title: string, subtitle = "none", footer?: string): string {
return `${title} | ${subtitle} | ${footer ?? "no footer"}`;
}
console.log(makeCard("Welcome"));
console.log(makeCard("Welcome", "Sub"));
console.log(makeCard("Welcome", "Sub", "End"));
// Output: Welcome | none | no footer
// Output: Welcome | Sub | no footer
// Output: Welcome | Sub | End
The default fills in subtitle, and the optional footer falls back with ??, so all three calls are valid.
Exercise 3 (Medium): Callback and Rest Parameters
Write a function applyAll(values: number[], fn: (n: number) => number): number[] that maps over the values. Then write a sum(...values: number[]): number function and call both.
Show solution
function applyAll(values: number[], fn: (n: number) => number): number[] {
return values.map(fn);
}
function sum(...values: number[]): number {
return values.reduce((t, v) => t + v, 0);
}
console.log(applyAll([1, 2, 3], (n) => n * 10));
console.log(sum(4, 5, 6));
// Output: [ 10, 20, 30 ]
// Output: 15
The callback parameter is typed with a function type expression, and the rest parameter collects all arguments into an array.
Exercise 4 (Challenge): Function Overload for a Parser
Write an overloaded function parse that accepts a string and returns a number, or accepts a number and returns a string. Show both calls and one invalid call that the compiler rejects.
Show solution
function parse(value: string): number;
function parse(value: number): string;
function parse(value: string | number): number | string {
if (typeof value === "string") {
return Number(value);
}
return String(value);
}
console.log(parse("42"));
console.log(parse(99));
// parse(true);
// Error: No overload matches this call.
// Output: 42
// Output: 99
The two signatures tell the compiler which input maps to which return. The implementation handles both, and true matches neither signature.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts.
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
