TypeScript / TypeScript Classes and Object-Oriented Programming

Creating Classes and Objects in TypeScript

In this tutorial, we will explore how to define classes and instantiate objects in TypeScript. We will also cover how to define properties and methods within a class.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

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

Introduction

This tutorial will guide you on how to create classes and objects in TypeScript. TypeScript, a statically typed superset of JavaScript, introduces the concept of types and classes, making it easier to structure your code in an object-oriented manner.

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

  • Define a class in TypeScript.
  • Instantiate objects from the class.
  • Add properties and methods to the class.

Prerequisites: Basic understanding of JavaScript and TypeScript syntax would be helpful, but not necessary as we will cover the basics.

Step-by-Step Guide

1. Defining a Class

In TypeScript, a class is defined using the keyword class followed by the name of the class. The class name is typically capitalized.

class MyClass { }

2. Class Properties

Inside the class, you can define properties (variables associated with the class). These properties will hold the state of the objects.

class MyClass {
    property1: string;
    property2: number;
}

3. Class Methods

Methods (functions associated with the class) can be defined inside the class. These methods can access the class properties and perform actions.

class MyClass {
    property1: string;
    property2: number;

    myMethod() {
        // actions here
    }
}

4. Creating Objects

You can create an object (instance of a class) using the new keyword followed by the class name and parentheses.

let myObject = new MyClass();

Code Examples

Here are some examples of classes and objects in TypeScript.

Example 1

Let's create a Person class with properties name and age, and a method introduce.

class Person {
    name: string;
    age: number;

    introduce() {
        console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
    }
}

let bob = new Person();
bob.name = "Bob";
bob.age = 25;
bob.introduce(); // Outputs: "Hello, my name is Bob and I am 25 years old."

Example 2

Let's add a constructor to our Person class. The constructor is a special method that is called when an object is created.

class Person {
    name: string;
    age: number;

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

    introduce() {
        console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
    }
}

let alice = new Person("Alice", 30);
alice.introduce(); // Outputs: "Hello, my name is Alice and I am 30 years old."

Summary

In this tutorial, you learned how to define a class in TypeScript, create objects from the class, and define properties and methods for the class. You also saw how to use a constructor to initialize the properties.

Next, you could learn about inheritance and interfaces in TypeScript, which will allow you to create more complex class structures.

Additional resources:
- TypeScript Handbook - Classes
- TypeScript for Beginners - Classes

Practice Exercises

  1. Create a Car class with properties brand, model, and year. Add a method displayCarInfo that outputs the car's information.

  2. Enhance the Car class by adding a constructor that initializes the brand, model, and year properties.

  3. Create a Student class with properties name, age, and grade. Add a method promote that increases the grade by one.

Solutions and explanations will be provided upon request.

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

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

Random Number Generator

Generate random numbers between specified ranges.

Use tool

Fake User Profile Generator

Generate fake user profiles with names, emails, and more.

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

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