Start learning free

LESSON 285 OF 675 · FUNCTIONS & CLASSES

Constructors in TypeScript

Lesson

TL ; DR:

  • A constructor is a special method that runs automatically when you create an object with new. It's used to set up the object's properties.


  • In TypeScript, the constructor is a method literally named constructor, defined inside the class. The fields it sets are declared first, with their types, and the parameters are typed too:

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

  • Then create objects with arguments: new Dog("Rex", 4) — the constructor fills in the properties for you.



Full lesson:

In the previous lesson you set properties one at a time after creating the object:

let dog = new Dog();
dog.name = "Rex";
dog.age = 4;

That works, but it's verbose and easy to forget. Constructors let you initialize the properties the moment new Dog(...) is called.


Defining a constructor

In TypeScript, the constructor is a method named exactly constructor:

class Dog {
    name: string;
    age: number;

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

The this keyword

this is a built-in reference to the object being created. this.name = name means "set the name property on this new object to the value of the name parameter".


Calling the constructor

let rex  = new Dog("Rex", 4);
let luna = new Dog("Luna", 7);

By the time these lines finish, rex.name is already "Rex", rex.age is 4, and the same for Luna.


Your task

Inside the Dog class, declare the fields name: string and age: number, then define a constructor that takes name and age and assigns them with this. Then below the class, create two dogs:

let rex: Dog  = new Dog("Rex", 4);
let luna: Dog = new Dog("Luna", 7);

Expected output:

Rex is 4
Luna is 7
STEP 1 OF 4
    Ctrl + Enter to check