Functions in TypeScript are similar to functions in JavaScript, but TypeScript allows you to define the types of the parameters and the return type of the function, adding type safety and improving the development experience. Here, we will cover various aspects of functions in TypeScript, including basic function syntax, optional and default parameters, rest parameters, function overloading, and more.
Basic Function Syntax
Here is a simple example of a function in TypeScript:
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("John")); // Output: Hello, John!
In this example:
name: string
specifies that the name
parameter must be a string.
: string
after the parentheses specifies that the function returns a string.
Function with Optional Parameters
You can define optional parameters using the ?
symbol:
function greet(name: string, age?: number): string {
if (age) {
return `Hello, ${name}. You are ${age} years old.`;
} else {
return `Hello, ${name}.`;
}
}
console.log(greet("John")); // Output: Hello, John.
console.log(greet("Tom", 25)); // Output: Hello, Tom. You are 25 years old.
Default Parameters
You can also provide default values for parameters:
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
console.log(greet("John")); // Output: Hello, John!
console.log(greet("Tom", "Hi")); // Output: Hi, Tom!
Rest Parameters
Rest parameters allow you to pass an arbitrary number of arguments to a function:
function sum(...numbers: number[]): number {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(1, 2, 3, 4, 5)); // Output: 15
Function Types
type GreetFunction = (name: string) => string;
const greet: GreetFunction = (name: string) => {
return `Hello, ${name}!`;
};
console.log(greet("John")); // Output: Hello, John!
Arrow Functions
TypeScript also supports arrow functions, which can be especially useful for inline functions:
const greet = (name: string): string => {
return `Hello, ${name}!`;
};
console.log(greet("John")); // Output: Hello, John!
Overloading
TypeScript allows you to define multiple signatures for a function:
function greet(name: string): string;
function greet(name: string, age: number): string;
function greet(name: string, age?: number): string {
if (age !== undefined) {
return `Hello, ${name}. You are ${age} years old.`;
} else {
return `Hello, ${name}.`;
}
}
console.log(greet("John")); // Output: Hello, John.
console.log(greet("Tom", 25)); // Output: Hello, Tom. You are 25 years old.
In this example, there are two function signatures for greet
, one with a single name
parameter and one with both name
and age
parameters. The implementation handles both cases.
These examples cover the basics of functions in TypeScript. You can use these concepts to write more complex functions as needed.