logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Understanding Classes in TypeScript

author
Generated by
Abhishek Goyan

17/10/2024

TypeScript

Sign in to read full article

TypeScript extends JavaScript by introducing strong typing and object-oriented programming concepts. One of the most important features in this paradigm is the class. Classes allow you to create blueprints for objects and define their properties and behaviors in a structured manner. Let's dive into the world of TypeScript classes!

Basic Syntax of Classes

At its core, a class in TypeScript is defined using the class keyword, followed by the class name. The body of the class contains the properties and methods.

class Animal { name: string; constructor(name: string) { this.name = name; } speak(): void { console.log(`${this.name} makes a noise.`); } }

Breakdown of the Example

  • Class Declaration: The class Animal defines a new class called Animal.
  • Properties: We declare a property name of type string.
  • Constructor: The constructor method is a special function that gets called when a new instance of the class is created.
  • Methods: The speak method outputs a message to the console.

Creating Instances

We can create an instance of the Animal class using the new keyword:

const dog = new Animal("Buddy"); dog.speak(); // Output: Buddy makes a noise.

Inheritance in Classes

One of the major advantages of using classes is inheritance. This allows one class to derive properties and methods from another class.

Example of Inheritance

class Dog extends Animal { speak(): void { console.log(`${this.name} barks.`); } } const dog = new Dog("Buddy"); dog.speak(); // Output: Buddy barks.

Breakdown of Inheritance

  • Extending Classes: The Dog class extends the Animal class, meaning it inherits all of its properties and methods.
  • Overriding Methods: The speak method in the Dog class overrides the same method in Animal, providing a specific implementation for dogs.

Access Modifiers

TypeScript also provides access modifiers that define the visibility of class members. The three main access modifiers are public, private, and protected.

Example with Access Modifiers

class Person { public name: string; private age: number; // Only accessible within this class protected species: string; // Accessible within this class and subclasses constructor(name: string, age: number, species: string) { this.name = name; this.age = age; this.species = species; } } const john = new Person("John", 30, "Homo Sapiens"); console.log(john.name); // Output: John // console.log(john.age); // Error: Property 'age' is private and only accessible within class 'Person'

Understanding Access Modifiers

  • Public: Members are accessible from anywhere.
  • Private: Members are only accessible within the class.
  • Protected: Members are accessible within the class and subclasses.

Static Methods and Properties

Static properties and methods belong to the class itself rather than instances of the class. They are useful for utility functions or constants.

Creating Static Members

class MathUtils { static PI: number = 3.14; static calculateCircumference(radius: number): number { return 2 * MathUtils.PI * radius; } } console.log(MathUtils.PI); // Output: 3.14 console.log(MathUtils.calculateCircumference(5)); // Output: 31.400000000000002

Breakdown of Static Members

  • Static Properties: PI is a static property accessible using the class name.
  • Static Methods: calculateCircumference can be called without creating an instance of MathUtils.

Abstract Classes

Abstract classes cannot be instantiated directly and are designed to be extended by other classes. This is useful for defining base classes for other derived classes.

Example of Abstract Classes

abstract class Shape { abstract getArea(): number; // Abstract method printArea(): void { console.log(`Area: ${this.getArea()}`); } } class Circle extends Shape { private radius: number; constructor(radius: number) { super(); this.radius = radius; } getArea(): number { return Math.PI * this.radius * this.radius; } }

Understanding Abstract Classes

  • Abstract Classes: The Shape class contains an abstract method getArea, which must be implemented by derived classes.
  • Derived Class: The Circle class implements the getArea method, providing a specific implementation.

By leveraging the power of classes in TypeScript, you can build clean, well-structured applications that are easier to maintain and extend. With the combination of inheritance, access modifiers, static members, and abstract classes, TypeScript's class system allows for robust object-oriented programming practices. Happy coding!

Popular Tags

TypeScriptclassesobject-oriented programming

Share now!

Like & Bookmark!

Related Collections

  • TypeScript Mastery: From Basics to Advanced

    17/10/2024 | TypeScript

Related Articles

  • Tooling with TypeScript

    17/10/2024 | TypeScript

  • Understanding Decorators in TypeScript

    17/10/2024 | TypeScript

  • Understanding Interfaces in TypeScript

    17/10/2024 | TypeScript

  • Demystifying Generics in TypeScript

    17/10/2024 | TypeScript

  • Understanding Basic Types in TypeScript

    17/10/2024 | TypeScript

  • Understanding Enums in TypeScript

    17/10/2024 | TypeScript

  • Understanding Functions in TypeScript

    17/10/2024 | TypeScript

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design