Lesson Overview

Hello there! Today, we're delving into TypeScript classes, focusing on attributes and methods. Attributes define properties, whereas methods define actions. Through the Dog class, you'll learn these concepts. By the end of the lesson, you should be capable of effectively using attributes and methods in TypeScript classes.

Understanding Attributes in TypeScript Classes

Attributes can be regarded as properties. For a Dog class, the attributes can include name: "Fido", breed: "Poodle", color: "White". These attributes depict a dog's characteristics, such as those of Fido.

Creating Attributes in a TypeScript Class

In the Dog class, we define attributes like name, breed, and color directly. These attributes represent a dog's characteristics and are set with default values:

To instantiate the class and access these attributes, you would do the following:

Here, Fido is an object of the Dog class.

Understanding Methods in TypeScript Classes

Methods are actions that instances of a class can execute. For the Dog class, behaviors might include bark(), eat(), and sleep(). These methods are functions defined in the class.

Creating Methods in a TypeScript Class

Let's enrich Fido's life with some actions. By introducing methods to the Dog class, we can enable him to bark, eat, and sleep:

Here, the bark, eat, and sleep methods determine a Dog object's behavior. Now, an instance of Dog can bark, eat, and sleep. Note the usage of this in the eat(food: string) method - here this refers to the current instance of the Dog class, referencing the class attribute.

Using Attributes and Methods in TypeScript Class Instances

Let's create an object from the Dog class and call its methods:

Equipped with attributes and methods, our Dog class truly comes alive!

Lesson Summary and Practice

That's about it! With attributes and methods, you can render TypeScript classes more interactive. In this lesson, the Dog class served to demonstrate the application of attributes and methods. Up next are exercises tailored for you to practice and hone these learned concepts. Happy coding!

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