Topic Overview

Hello and welcome to another exciting course in your learning journey! Today, we'll be delving into a core concept of Object-Oriented Programming (OOP): TypeScript classes. These classes act as templates, permitting us to craft objects — instances of these templates — each with unique attributes and behaviors. The objective of this lesson is to understand what classes are, how to create them, and their role within TypeScript coding.

Understanding Classes in TypeScript

A TypeScript class can be considered a construction blueprint. By adhering to this blueprint, we can create objects with specific structures, each holding variable values.

class Fruit {
}

Here, Fruit is our blueprint or class. This blueprint enables us to generate an array of fruit objects, each with distinctive characteristics, resembling the construction of a building.

Creating an Instance of a Class

Creating an instance of a class — essentially animating an object from a blueprint — involves the new keyword:

let apple = new Fruit();

In this case, apple is a specific instance or object of our Fruit class, much like a single building erected from a common blueprint.

Incorporating Methods Inside a Class

To give our class some actions, we add methods — actions that objects created from the class can perform. We will look at two methods within our Fruit class: printColor and printMessage.

class Fruit {
  printColor() {
    console.log('Red'); // Prints 'Red' to the console
  }

  printMessage(name: string) {
    console.log(`Do you want a fruit, ${name}?`); // Greets and asks the user if they want a fruit
  }
}

The first method, printColor, is a straightforward function that when called, prints Red to the console. This method doesn't take any parameters and its purpose is to showcase the color of the fruit.

The second method, printMessage, takes one parameter of type stringname. It uses this parameter to personalize a message, thus illustrating how methods can interact with data passed to them. When called, it prints a message in the format "Do you want a fruit, [name]?", where [name] is replaced with the actual string argument provided during the method call.

Notice that we've omitted the function keyword in both cases — that's a part of the TypeScript class syntax.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal