TypeScript / TypeScript Classes and Object-Oriented Programming

Understanding Access Modifiers in Classes

This tutorial will delve into access modifiers in TypeScript classes. We will learn about public, private, and protected modifiers and their uses.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores object-oriented principles in TypeScript, including classes, inheritance, and access modifiers.

Understanding Access Modifiers in Classes

1. Introduction

In this tutorial, we aim to understand access modifiers in TypeScript classes. We will explore public, private, and protected modifiers, their features, and practical uses.

By the end of this guide, you will be able to:

  • Understand and use different access modifiers
  • Develop and design TypeScript classes more effectively

Prerequisites: Basic knowledge of TypeScript and object-oriented programming concepts is beneficial.

2. Step-by-Step Guide

Access modifiers in TypeScript are used to set accessibility boundaries for properties, methods, and other members of a class. There are three types of access modifiers: public, private, and protected.

Public: This is the default modifier and accessible anywhere without any restrictions.

Private: These members are only accessible within the class that defines them.

Protected: This is similar to private, but these members can also be accessed within subclasses.

Best Practices and Tips

  • Use the private modifier to hide implementation details and prevent external manipulation.
  • The protected modifier is useful when you're writing a class that's intended to be subclassed.
  • Even though public is the default, explicitly labeling public members can make your code more readable.

3. Code Examples

Example 1: Public Modifier

class Car {
  public make: string; // This can be accessed anywhere

  constructor(make: string) {
    this.make = make;
  }
}

const myCar = new Car('Toyota');
console.log(myCar.make); // Outputs: Toyota

In this example, make is a public property of the Car class, meaning it can be accessed directly from an instance of the class (myCar).

Example 2: Private Modifier

class Car {
  private miles: number; // This can only be accessed within the Car class

  constructor() {
    this.miles = 0;
  }

  drive(distance: number) {
    this.miles += distance;
  }

  getMiles() {
    return this.miles;
  }
}

const myCar = new Car();
myCar.drive(100);
console.log(myCar.getMiles()); // Outputs: 100
// console.log(myCar.miles); would cause an error

In this example, miles is a private property. It can't be accessed directly from myCar; instead, we provide a getMiles method to access it.

4. Summary

We've learned about access modifiers and how they can help us manage the accessibility of our class members. Public, private, and protected modifiers each have their own use cases and should be chosen appropriately to design robust classes.

For the next steps, practice using these modifiers in your own classes. You can also explore TypeScript's official documentation for more concepts.

5. Practice Exercises

Exercise 1: Create a Person class with public name, private age, and a public method getAge which returns age.

Exercise 2: Extend the Person class to create a Student class. Add a protected grades property and a method to access it.

Solutions:

Exercise 1:

class Person {
  public name: string;
  private age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  getAge() {
    return this.age;
  }
}

Exercise 2:

class Student extends Person {
  protected grades: number[];

  constructor(name: string, age: number, grades: number[]) {
    super(name, age);
    this.grades = grades;
  }

  getGrades() {
    return this.grades;
  }
}

Remember, the key to understanding is consistent practice. Keep experimenting with different scenarios and the application of these modifiers.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Image Converter

Convert between different image formats.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help