TypeScript allows you to define functions with explicit argument and return types. This ensures type safety and helps catch errors at compile time.
Defining Argument and Return Types
You can annotate each parameter with its type and the return type after the function's parentheses.
Syntax:
function functionName(param1: Type1, param2: Type2): ReturnType {
// function body
}
Example 1: Simple Addition
function add(a: number, b: number): number {
return a + b;
}
-
aandbare both required to be numbers. - The function returns a number.
Example 2: String Formatter
function greet(name: string): string {
return `Hello, ${name}!`;
}
- The parameter
namemust be a string. - The function returns a string.
Using Arrow Functions
You can also define typed arguments and return types in arrow functions.
const multiply = (x: number, y: number): number => x * y;
Benefits
- Prevents passing or returning incorrect types
- Improves code documentation and readability
Tip
If a function doesnโt return anything, use void as the return type:
function logMessage(msg: string): void {
console.log(msg);
}
Top comments (0)