Start learning free

LESSON 286 OF 675 · FUNCTIONS & CLASSES

Object Properties in TypeScript

Lesson

TL ; DR:

  • A property is a piece of data attached to an object. You declare each property in the class body with its type, then assign it with the dot operator:

    class Dog {
        name: string;
        age: number;
    }
    
    let dog = new Dog();
    dog.name = "Rex";
    dog.age = 4;
    

  • Each object has its own properties, so two dogs can have different names without interfering.



Full lesson:

Right now your Dog class is just an empty shell — every Dog object you create is identical. We need a way to attach data to each object.

In TypeScript, the data attached to an object is called a property. (Other languages call them fields or attributes — same idea.)


Setting properties

In TypeScript you declare each property in the class body, with its type (name: string;, age: number;). Then assign to it with the dot operator:

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

After this, dog has a name property equal to "Rex" and an age property equal to 4.


Reading properties

console.log(dog.name);   // Rex
console.log(dog.age);    // 4

You read properties the same way you set them — with the dot operator.


Each object has its own properties

let rex = new Dog();
let luna = new Dog();
rex.name = "Rex";
luna.name = "Luna";
// rex.name is "Rex", luna.name is "Luna" — they don't interfere.

Your task

The Dog class is already defined for you. Below it, set dog.name to "Rex" and dog.age to 4. The pre-filled console.log will then show:

Rex is 4 years old
STEP 1 OF 1
    Ctrl + Enter to check