Functions:
1. Function Declaration:
- Functions in TypeScript can be declared using the
function
keyword, followed by the function name and parameter list. - Example:
- function greet(name: string): void { console.log(`Hello, ${name}!`); }
2. Function Parameters and Return Types:
- TypeScript allows specifying parameter types and return types for functions.
- Example:
- function add(x: number, y: number): number { return x + y; }
3. Optional and Default Parameters:
- Parameters in TypeScript functions can be made optional by appending a
?
after the parameter name. Default values can also be provided. - Example:
- function greet(name: string, greeting: string = 'Hello'): void { console.log(`${greeting}, ${name}!`); }
4. Rest Parameters:
- TypeScript supports rest parameters, which allow passing an arbitrary number of arguments to a function as an array.
- Example:
- function sum(...numbers: number[]): number { return numbers.reduce((total, num) => total + num, 0); }
Classes:
1. Class Declaration:
- Classes are blueprints for creating objects in TypeScript, encapsulating data and behavior.
- You declare a class using the
class
keyword followed by the class name. - Example:
- class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } greet(): void { console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`); } }
2. Constructors:
- Classes can have a special method called a constructor, which is executed when an instance of the class is created.
- The constructor initializes object properties and can take parameters.
- Example:
- class Person { constructor(public name: string, public age: number) { } // Other methods... }
3. Access Modifiers:
- TypeScript supports access modifiers (
public
,private
, andprotected
) to control the accessibility of class members. - Example:
- class Person { private email: string; constructor(public name: string, private age: number) { this.email = 'example@example.com'; } // Other methods... }
4. Inheritance:
- TypeScript supports inheritance, allowing classes to inherit properties and methods from other classes using the
extends
keyword. - Example:
- class Student extends Person { constructor(name: string, age: number, public grade: string) { super(name, age); } // Additional methods... }
5. Static Members:
- Static members belong to the class itself rather than instances of the class. They are accessed using the class name.
- Example:
- class MathOperations { static PI: number = 3.14; static circumference(radius: number): number { return 2 * this.PI * radius; } }
Example: Building a Simple Calculator
In this example, we'll create a simple calculator using TypeScript. We'll define a class Calculator
with methods for basic arithmetic operations like addition, subtraction, multiplication, and division.
// Define a class Calculator class Calculator { // Method to add two numbers add(x: number, y: number): number { return x + y; } // Method to subtract two numbers subtract(x: number, y: number): number { return x - y; } // Method to multiply two numbers multiply(x: number, y: number): number { return x * y; } // Method to divide two numbers divide(x: number, y: number): number { if (y === 0) { throw new Error('Division by zero is not allowed'); } return x / y; } } // Create an instance of Calculator const calc = new Calculator(); // Perform arithmetic operations console.log('Addition:', calc.add(5, 3)); // Output: 8 console.log('Subtraction:', calc.subtract(5, 3)); // Output: 2 console.log('Multiplication:', calc.multiply(5, 3)); // Output: 15 console.log('Division:', calc.divide(10, 2)); // Output: 5
Explanation:
- We define a class
Calculator
with methods for performing basic arithmetic operations: add
, subtract
, multiply
, and divide
. - Each method takes two parameters (
x
and y
) representing the operands and returns the result of the respective operation. - In the
divide
method, we handle the special case of division by zero by throwing an error. - We create an instance of
Calculator
using the new
keyword and call its methods to perform arithmetic operations.
- We define a class
Calculator
with methods for performing basic arithmetic operations:add
,subtract
,multiply
, anddivide
. - Each method takes two parameters (
x
andy
) representing the operands and returns the result of the respective operation. - In the
divide
method, we handle the special case of division by zero by throwing an error. - We create an instance of
Calculator
using thenew
keyword and call its methods to perform arithmetic operations.
Summary:
This example demonstrates the use of classes and methods in TypeScript to build a simple calculator. Classes help in organizing code and encapsulating behavior, making it easier to manage and maintain. By defining methods within classes, we can create reusable components with well-defined functionality.
This example demonstrates the use of classes and methods in TypeScript to build a simple calculator. Classes help in organizing code and encapsulating behavior, making it easier to manage and maintain. By defining methods within classes, we can create reusable components with well-defined functionality.
Functions and classes in TypeScript provide a robust mechanism for defining behavior and organizing code. Functions encapsulate behavior, while classes encapsulate both data and behavior, facilitating modularity, reusability, and maintainability in your TypeScript projects. By understanding and leveraging these features, you can build scalable and structured applications more effectively.
0 Comments