- TypeScript Tutorial
- TypeScript Home
- TypeScript Introduction
- TypeScript Setup
- TypeScript First Program
- TypeScript vs JavaScript
- TypeScript Data Types
- TypeScript Type Inference
- TypeScript Type Annotations
- TypeScript Interfaces
- TypeScript Enums
- TypeScript Type Aliases
- TypeScript Type Assertions
- TypeScript Variables
- TypeScript Functions
- TypeScript Functions
- TypeScript Optional Parameters
- TypeScript Default Parameters
- TypeScript Rest Parameters
- TypeScript Arrow Functions
- Classes and Objects
- Introduction to Classes
- Properties and Methods
- Access Modifiers
- Static Members
- Inheritance
- Abstract Classes
- Interfaces vs Classes
- Advanced Types
- TypeScript Union Types
- TypeScript Intersection Types
- TypeScript Literal Types
- TypeScript Nullable Types
- TypeScript Type Guards
- TypeScript Discriminated Unions
- TypeScript Index Signatures
- TypeScript Generics
- Introduction to Generics
- TypeScript Generic Functions
- TypeScript Generic Classes
- TypeScript Generic Constraints
- TypeScript Modules
- Introduction to Modules
- TypeScript Import and Export
- TypeScript Default Exports
- TypeScript Namespace
- Decorators
- Introduction to Decorators
- TypeScript Class Decorators
- TypeScript Method Decorators
- TypeScript Property Decorators
- TypeScript Parameter Decorators
- Configuration
- TypeScript tsconfig.json File
- TypeScript Compiler Options
- TypeScript Strict Mode
- TypeScript Watch Mode
TypeScript Functions
Functions are the fundamental building blocks of any application. In TypeScript, they take the flexibility of JavaScript and add a layer of "contractual" safety. By defining types for your inputs (parameters) and outputs (return values), you catch bugs during development rather than at runtime. This turns your functions into self-documenting code that tells other developers exactly what to expect.
Syntax for Functions
Basic Syntax:
A TypeScript function looks very similar to JavaScript, but with type annotations added after the parameters and before the curly braces.
function functionName(param1: type, param2: type): returnType {
// function body
return value;
}
string, TypeScript will highlight an error if you try to return a number.
Function Types
Functions with Parameter Types and Return Types
- Adding types prevents common "undefined" errors. For example, if a function expects a
numberand you pass astring, the compiler will stop you immediately.
Optional Parameters
- In some cases, a function doesn't need every piece of data to run. You can make a parameter optional by adding a
?after its name. Important: Optional parameters must always appear after any required parameters.
function greet(name: string, greeting?: string): string {
return greeting ? `${greeting}, ${name}!` : `Hello, ${name}!`;
}
Default Parameters
- If you want a parameter to have a fallback value when nothing is provided, use default parameters. This also makes the parameter optional for the caller.
?) and give it a default value. The default value already implies that the parameter is optional.
Rest Parameters
- When you don't know how many arguments a user will pass (like summing a list of numbers), use rest parameters. The
...syntax collects multiple arguments into a single array.
function sumAll(...numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}
Anonymous Functions
Anonymous functions (functions without a name) are often used when passing a function as an argument to another function, or when assigning a function to a constant.
const multiply = function (a: number, b: number): number {
return a * b;
};
console.log(multiply(5, 3)); // Output: 15
Arrow Functions
Arrow functions are the modern standard in React and Node.js development. They provide a shorter syntax and handle the this keyword more predictably in classes.
const subtract = (a: number, b: number): number => a - b;
console.log(subtract(10, 3)); // Output: 7
.map() or .filter().
Function Overloading
Sometimes a single function needs to handle different types of inputs and return different types of results based on those inputs. Function overloading allows you to define multiple "shapes" for the same function.
// Overload signatures
function combine(a: string, b: string): string;
function combine(a: number, b: number): number;
// Actual implementation
function combine(a: any, b: any): any {
return a + b;
}
console.log(combine(5, 10)); // Output: 15
console.log(combine("Hello, ", "World!")); // Output: Hello, World!
Void Return Type
If a function performs an action (like logging to a console or saving to a database) but doesn't send a value back to the caller, use void.
function logMessage(message: string): void {
console.log(message);
}
logMessage("Hello, TypeScript!"); // Output: Hello, TypeScript!
Never Return Type
The never type is rare but powerful. It represents a function that never finishes successfully. This happens if the function always throws an error or enters an infinite loop.
function handleCriticalError(message: string): never {
throw new Error(message);
}
Example: Function with Multiple Features
In real-world projects, you’ll often mix these concepts. Here is a function that uses a required parameter, an optional parameter, and rest parameters together.
function displayInfo(name: string, age?: number, ...hobbies: string[]): string {
const ageInfo = age ? `, Age: ${age}` : "";
const hobbiesInfo = hobbies.length ? `, Hobbies: ${hobbies.join(", ")}` : "";
return `Name: ${name}${ageInfo}${hobbiesInfo}`;
}
console.log(displayInfo("John"));
console.log(displayInfo("Alice", 25, "Reading", "Traveling"));
Output:
Name: John
Name: Alice, Age: 25, Hobbies: Reading, Traveling
string[] or number[]) to prevent accidental type mixing inside the function body.
Summary
Mastering functions in TypeScript is about more than just syntax—it's about writing code that is predictable and easy to maintain. By utilizing parameter types, optional values, and specific return types like void or never, you create a safety net for your future self and your teammates. Whether you are using traditional declarations or concise arrow functions, TypeScript ensures that your logic remains robust as your application scales.