Functions and Methods in TypeScript - A Beginner's Tutorial


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.


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

Function Parameters

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


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.


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("John", "Doe"));

Function Expressions

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


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.


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.


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);


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.