TypeScript Functions: How to Use Parameters and Return Types
Functions are the building blocks of any programming language, and TypeScript enhances them by adding type safety. By defining types for parameters and return values, TypeScript allows developers to write more reliable and maintainable code. This guide will introduce you to TypeScript functions, covering how to use parameters and return types effectively.
Defining a Function in TypeScript
In TypeScript, functions can be defined using the function
keyword, similar to JavaScript. However, TypeScript allows you to specify the types of parameters and return values for additional safety and readability.
Basic Function Example
Here’s an example of a basic TypeScript function with typed parameters and a return type:
function add(a: number, b: number): number {
return a + b;
}
const result = add(5, 3); // Output: 8
In this example, the add
function accepts two parameters of type number
and returns a value of type number
. This ensures that both the input and output conform to the expected types.
Function Parameters in TypeScript
TypeScript functions can accept various types of parameters, such as optional, default, and rest parameters. Let’s explore each type in detail.
Optional Parameters
You can define optional parameters by adding a ?
after the parameter name. Optional parameters do not need to be provided when the function is called.
function greet(name: string, age?: number): string {
if (age) {
return `Hello, ${name}. You are ${age} years old.`;
} else {
return `Hello, ${name}.`;
}
}
console.log(greet("Alice")); // Output: Hello, Alice.
console.log(greet("Bob", 25)); // Output: Hello, Bob. You are 25 years old.
In this example, the age
parameter is optional. The function works correctly whether the age
is provided or not.
Default Parameters
Default parameters allow you to specify default values for parameters in case they are not provided when the function is called.
function multiply(a: number, b: number = 2): number {
return a * b;
}
console.log(multiply(5)); // Output: 10
console.log(multiply(5, 3)); // Output: 15
In this example, the b
parameter has a default value of 2
. If no second argument is provided, 2
will be used by default.
Rest Parameters
Rest parameters allow you to pass a varying number of arguments to a function. They are defined using the ...
syntax.
function sum(...numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10
console.log(sum(5, 10, 15)); // Output: 30
In this example, the sum
function accepts any number of arguments, all of type number
, and returns their sum.
Return Types in TypeScript
Specifying the return type of a function is as important as defining parameter types. It helps TypeScript understand the expected output of the function, ensuring it returns the correct type of data.
Specifying Return Types
To specify the return type of a function, add a colon :
followed by the type after the parameter list.
function isEven(num: number): boolean {
return num % 2 === 0;
}
console.log(isEven(4)); // Output: true
console.log(isEven(5)); // Output: false
In this example, the isEven
function returns a boolean
indicating whether the input number is even or not.
Functions with No Return Type
When a function does not return a value, its return type is void
. This is useful for functions that perform an action without providing a result.
function logMessage(message: string): void {
console.log(message);
}
logMessage("Hello, TypeScript!"); // Output: Hello, TypeScript!
In this example, the logMessage
function logs a message to the console and returns nothing, hence the return type is void
.
Conclusion
TypeScript functions provide a powerful way to write type-safe code by defining parameter types and return types. By using optional, default, and rest parameters, as well as specifying return types, you can create more robust and maintainable functions. Start using TypeScript functions in your projects to ensure better code quality and safety.