Parameter Typing, Return Types, and Modern Syntax - Textnotes

Parameter Typing, Return Types, and Modern Syntax


Learn how to define and use functions in TypeScript with proper typing. This module explains function parameter typing, return types, optional and default parameters, and arrow functions with clear, real-world examples.

1. Function Parameter Typing

In TypeScript, function parameters are strongly typed. This ensures that functions receive the correct type of input and prevents runtime errors.

Example


function add(a: number, b: number) {
return a + b;
}

If a value of an incorrect type is passed, TypeScript produces a compile-time error.

Why Parameter Typing Is Important

Parameter typing improves code reliability, readability, and collaboration in team-based projects.

2. Return Types

Return types define the type of value a function returns. Although TypeScript can infer return types, explicitly specifying them is recommended for clarity and maintainability.

Example


function multiply(a: number, b: number): number {
return a * b;
}

Void Return Type

The void return type is used when a function does not return any value.


function logMessage(message: string): void {
console.log(message);
}

3. Optional Parameters

Optional parameters allow a function to accept fewer arguments. They are marked using a question mark and must be placed after required parameters.

Example


function greet(name: string, title?: string): string {
if (title) {
return `Hello ${title} ${name}`;
}
return `Hello ${name}`;
}

Valid Function Calls


greet("Muni");
greet("Muni", "Mr");

Optional parameters are commonly used when values are not always required.

4. Default Parameters

Default parameters assign a default value to a parameter when no value is provided during the function call.

Example


function calculateDiscount(price: number, discount: number = 10): number {
return price - (price * discount / 100);
}

If the discount parameter is omitted, the function uses the default value.

5. Arrow Functions

Arrow functions provide a concise syntax and automatically bind the this keyword, making them ideal for callbacks and modern frameworks.

Basic Arrow Function


const square = (num: number): number => {
return num * num;
};

Short Form Arrow Function


const double = (value: number): number => value * 2;

Arrow functions are widely used in React, Angular, and Node.js applications.

Conclusion

Functions in TypeScript provide strong type safety and clarity compared to JavaScript. By using typed parameters, defined return types, optional and default parameters, and arrow functions, developers can build reliable and maintainable applications.