Functions and classes help you organize your code into reusable blocks. Functions do tasks, and classes create objects with properties and actions.
0
0
Declaring functions and classes in Typescript
Introduction
When you want to repeat a task many times without rewriting code.
When you want to group related data and actions together, like a user or a car.
When you want to make your code easier to read and maintain.
When you want to create multiple similar objects with shared behavior.
When you want to separate your program into smaller, manageable parts.
Syntax
Typescript
function functionName(parameters): returnType { // code to run } class ClassName { propertyName: type; constructor(parameters) { // initialize properties } methodName(parameters): returnType { // code to run } }
Functions start with the function keyword, followed by a name and parentheses.
Classes use the class keyword and can have properties, a constructor, and methods.
Examples
A simple function that says hello to a name.
Typescript
function greet(name: string): void { console.log(`Hello, ${name}!`); }
A class that stores a person's name and can say hi.
Typescript
class Person { name: string; constructor(name: string) { this.name = name; } sayHi(): void { console.log(`Hi, I'm ${this.name}`); } }
A function that adds two numbers and returns the result.
Typescript
function add(a: number, b: number): number { return a + b; }
Sample Program
This program defines a function to multiply two numbers and a class to represent a rectangle with an area method. It prints the multiplication result and the rectangle's area.
Typescript
function multiply(x: number, y: number): number { return x * y; } class Rectangle { width: number; height: number; constructor(width: number, height: number) { this.width = width; this.height = height; } area(): number { return this.width * this.height; } } console.log(multiply(4, 5)); const rect = new Rectangle(3, 7); console.log(rect.area());
OutputSuccess
Important Notes
Use void as the return type when a function does not return a value.
Inside classes, this refers to the current object.
Always initialize class properties in the constructor to avoid errors.
Summary
Functions perform tasks and can return results.
Classes group data and actions to create objects.
Use functions and classes to write clean, reusable code.