TypeScript is an open-source programming language developed by Microsoft, which extends JavaScript by adding optional static typing and class-based object-oriented programming. In TypeScript, multiple object-oriented programming principles can be implemented, including the following key principles:
-
Encapsulation: Encapsulation is a fundamental principle of object-oriented programming, involving combining an object's data (properties) and methods (functions) while hiding internal details and implementation logic, exposing only necessary parts for external access. TypeScript supports encapsulation through classes, allowing the use of access modifiers such as
public,private, andprotectedto control access levels.Example:
typescriptclass Person { private name: string; constructor(name: string) { this.name = name; } public getName(): string { return this.name; } } let person = new Person("John"); console.log(person.getName()); // Correct access // console.log(person.name); // Error: 'name' property is private. -
Inheritance: Inheritance allows new object classes to inherit properties and methods from existing object classes, promoting code reuse and enabling polymorphism. TypeScript supports class inheritance using the
extendskeyword.Example:
typescriptclass Animal { public move(distance: number): void { console.log(`Animal moved ${distance}m.`); } } class Dog extends Animal { bark() { console.log('Woof! Woof!'); } } const dog = new Dog(); dog.bark(); dog.move(10); -
Polymorphism: Polymorphism allows subclasses to provide different implementations for the same method defined in their parent class. In TypeScript, this is typically achieved through method overriding.
Example:
typescriptclass Animal { makeSound() { console.log("Some generic sound"); } } class Dog extends Animal { makeSound() { console.log("Woof! Woof!"); } } let pet: Animal = new Dog(); pet.makeSound(); // Outputs "Woof! Woof!" -
Abstraction: Abstract classes and interfaces define structures to be implemented by other classes. Abstract classes enable the creation of non-instantiable classes that define or partially implement methods, while interfaces solely define the structure of methods and properties without implementation.
Example:
typescriptinterface Movable { move(): void; } class Car implements Movable { move() { console.log("Car moves"); } } class Bicycle implements Movable { move() { console.log("Bicycle moves"); } } let car: Movable = new Car(); let bike: Movable = new Bicycle(); car.move(); bike.move();
Through these principles, TypeScript provides robust object-oriented programming capabilities, making code more modular, manageable, and extensible.