Functions & Types in TypeScript (Live Playground)
In this tutorial, we will explore functions and types in TypeScript. Understanding how to create and use functions with type annotations will help you write cleaner, more maintainable, and type-safe code.
Functions
Functions are reusable blocks of code that perform a specific task. Functions help you write modular and more maintainable code. In TypeScript, you can define functions using the function
keyword:
function greet(name: string): string {
return `Hello, ${name}!`;
}
let message = greet('John');
console.log(message); // Output: Hello, John!
Function Types
In TypeScript, you can define a function type using type annotations. Function types allow you to specify the parameter types and return type of a function. Here's an example:
type GreetingFunction = (name: string) => string;
In this example, we define a function type called GreetingFunction
that takes a single string
parameter and returns a string
. We can use this function type to ensure that a variable or function parameter has a specific function signature:
const sayHello: GreetingFunction = (name: string) => {
return `Hello, ${name}!`;
};
console.log(sayHello('Jane')); // Output: Hello, Jane!
Optional Parameters
TypeScript allows you to define optional parameters for your functions using the ?
notation. Optional parameters must be placed after required parameters:
function greet(name: string, title?: string): string {
if (title) {
return `Hello, ${title} ${name}!`;
}
return `Hello, ${name}!`;
}
console.log(greet('John')); // Output: Hello, John!
console.log(greet('John', 'Mr.')); // Output: Hello, Mr. John!
Default Parameters
You can also provide default values for function parameters. If a value is not provided for a parameter with a default value, the default value will be used:
function greet(name: string, title: string = 'Friend'): string {
return `Hello, ${title} ${name}!`;
}
console.log(greet('John')); // Output: Hello, Friend John!
console.log(greet('John', 'Mr.')); // Output: Hello, Mr. John!
Rest Parameters
Rest parameters allow you to pass an arbitrary number of arguments to a function as an array. To define a rest parameter, use the ...
notation followed by the parameter name and type:
function greetAll(message: string, ...names: string[]): void {
for (const name of names) {
console.log(`${message}, ${name}!`);
}
}
greetAll('Hi', 'Alice', 'Bob', 'Charlie'); // Outputs Hi, Alice! Hi, Bob! Hi, Charlie!
Conclusion
In this tutorial, we have explored functions and types in TypeScript. Understanding how to create and use functions with type annotations, optional parameters, default parameters, and rest parameters will help you write cleaner, more maintainable, and type-safe code.