TypeScript Function: Syntax, Usage, and Examples
A TypeScript function is a reusable block of code that takes input, processes it, and returns an output. Strong typing makes TypeScript functions safer, reducing runtime errors and improving maintainability. Whether you’re defining functions, passing them as arguments, or using async/await, TypeScript ensures correctness through its type system.
How to Use Functions in TypeScript
Declaring a Function
To define a function, use the function keyword, followed by a name, parameter types, and a return type.
tsx
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Output: Hello, Alice!
Assigning Function Types
In TypeScript, you can specify function types explicitly, making it easier to define reusable patterns.
tsx
let add: (a: number, b: number) => number;
add = (x, y) => x + y;
console.log(add(5, 10)); // Output: 15
Function Parameters and Default Values
You can assign default values to function parameters, reducing the need for extra conditionals.
tsx
function greetUser(name: string = "Guest"): string {
return `Welcome, ${name}!`;
}
console.log(greetUser()); // Output: Welcome, Guest
Function Return Types
Functions can return different types depending on conditions.
tsx
function getResult(value: boolean): string | number {
return value ? "Success" : 0;
}
When to Use Functions in TypeScript
Reusability
If you find yourself writing the same logic multiple times, a function can simplify your code by keeping it in one place.
tsx
function calculateDiscount(price: number, discount: number): number {
return price - price * (discount / 100);
}
console.log(calculateDiscount(100, 10)); // Output: 90
Encapsulation
Functions help organize code by grouping related logic together.
tsx
function getFullName(firstName: string, lastName: string): string {
return `${firstName} ${lastName}`;
}
Working with Objects
You can define functions within objects to create methods that act on object properties.
tsx
const user = {
name: "Alice",
greet() {
return `Hello, ${this.name}!`;
},
};
console.log(user.greet()); // Output: Hello, Alice!
Examples of Functions in TypeScript
Function Overloading
Function overloading lets you define multiple function signatures with different parameter types.
tsx
function getInfo(value: string): string;
function getInfo(value: number): number;
function getInfo(value: string | number): string | number {
return typeof value === "string" ? `User: ${value}` : value * 2;
}
console.log(getInfo("Alice")); // Output: User: Alice
console.log(getInfo(10)); // Output: 20
Arrow Functions
Arrow functions provide a more concise syntax.
tsx
const square = (num: number): number => num * num;
console.log(square(4)); // Output: 16
Async Functions
Async functions handle asynchronous operations using async and await.
tsx
async function fetchData(url: string): Promise<string> {
const response = await fetch(url);
return response.text();
}
Passing Functions as Parameters
A function can be passed as an argument to another function.
tsx
function execute(callback: (message: string) => void) {
callback("Task completed!");
}
execute((msg) => console.log(msg)); // Output: Task completed!
Functions in Objects
Functions can also be stored in objects as properties.
tsx
const person = {
name: "Alice",
greet: function () {
return `Hello, my name is ${this.name}`;
},
};
console.log(person.greet()); // Output: Hello, my name is Alice
Learn More About TypeScript Functions
Function Types
Function types explicitly define the shape of a function, ensuring it follows a specific structure.
tsx
type MathOperation = (a: number, b: number) => number;
const subtract: MathOperation = (a, b) => a - b;
console.log(subtract(10, 5)); // Output: 5
Function Signatures
A function signature describes the expected structure of a function, making it easier to define consistent function types.
tsx
type Logger = (message: string) => void;
const log: Logger = (msg) => console.log(msg);
log("Logging message"); // Output: Logging message
Optional Function Parameters
You can make function parameters optional using ?.
tsx
function greetPerson(name: string, age?: number): string {
return age ? `${name} is ${age} years old.` : `Hello, ${name}!`;
}
console.log(greetPerson("Bob")); // Output: Hello, Bob!
console.log(greetPerson("Alice", 30)); // Output: Alice is 30 years old.
Function Overloading in Objects
Function overloading is also useful when defining methods in objects.
tsx
const calculator = {
add(a: number, b: number): number;
add(a: string, b: string): string;
add(a: number | string, b: number | string): number | string {
return typeof a === "number" && typeof b === "number"
? a + b
: `${a}${b}`;
},
};
console.log(calculator.add(5, 10)); // Output: 15
console.log(calculator.add("Hello, ", "World!")); // Output: Hello, World!
Exporting and Importing Functions
You can export and import functions between files in TypeScript.
tsx
// utils.ts
export function multiply(a: number, b: number): number {
return a * b;
}
// main.ts
import { multiply } from "./utils";
console.log(multiply(2, 3)); // Output: 6
Using Functions with Arrays
Functions can be used with array methods like map, filter, and reduce.
tsx
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((num) => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8, 10]
Handling Async Functions in Objects
Objects can contain asynchronous functions to handle async operations.
tsx
const api = {
async fetchData(url: string): Promise<string> {
const response = await fetch(url);
return response.text();
},
};
// Usage
api.fetchData("https://example.com").then((data) => console.log(data));
TypeScript functions improve code reliability and maintainability by enforcing type safety. Whether you’re using function types, optional parameters, async functions, or function overloading, TypeScript ensures that your functions behave as expected.
Looking to dive deeper into TypeScript functions and other essential TypeScript concepts? Check out our TypeScript course.