Functions and Methods in TypeScript - A Beginner's Tutorial


Introduction

Functions are fundamental in programming as they allow you to encapsulate and reuse blocks of code. In TypeScript, functions play a vital role in structuring your code. Let's explore how to declare, use, and work with functions and methods in TypeScript.


Declaring Functions

In TypeScript, you can declare functions using the function keyword.


Example:

function greet(name: string): string {
return "Hello, " + name + "!";
}
let message: string = greet("TypeScript");
console.log(message);

Function Parameters

Functions can take parameters, which are values you pass into the function when you call it.


Example:

function add(a: number, b: number): number {
return a + b;
}
let result: number = add(5, 3);
console.log("Sum:", result);

Function Overloading

Function overloading allows you to define multiple function signatures for the same function with different parameter types.


Example:

function greet(name: string): string;
function greet(firstName: string, lastName: string): string;
function greet(a: string, b?: string): string {
if (b) {
return "Hello, " + a + " " + b + "!";
} else {
return "Hello, " + a + "!";
}
}
console.log(greet("TypeScript"));
console.log(greet("John", "Doe"));

Function Expressions

You can also define functions as expressions and assign them to variables.


Example:

const multiply = function(a: number, b: number): number {
return a * b;
};
let product = multiply(4, 3);
console.log("Product:", product);

Arrow Functions

Arrow functions provide a concise way to define functions, especially when the function is simple and has a single expression.


Example:

const divide = (a: number, b: number): number => a / b;
let quotient = divide(10, 2);
console.log("Quotient:", quotient);

Methods in Classes

In TypeScript, you can define methods within classes. Methods are functions that are associated with objects created from the class.


Example:

class Calculator {
add(a: number, b: number): number {
return a + b;
}
}
const calc = new Calculator();
let sum = calc.add(7, 3);
console.log("Sum:", sum);

Conclusion

Functions and methods are crucial in TypeScript for organizing, encapsulating, and reusing code. As you continue your TypeScript journey, you'll find yourself defining and using functions and methods extensively to build efficient and maintainable software. Explore more advanced topics like function types, higher-order functions, and more as you advance in TypeScript development.