⊗tsSpOpCP 4 of 37 menu

OOP Class Properties in TypeScript

Now let's learn how to declare class properties. In TypeScript, all properties must be declared with their type. Let's see how this is done in practice.

Let's create a class User. Let's give it a property name, specifying that it will be a string:

class User { name: string; }

This code, however, will throw an error because the initial value of the property is not set.

Let's ask it:

class User { name: string = 'john'; }

Now let's make an object of our class:

let user: User = new User;

Now let's output the value of the property:

console.log(user.name); // 'john'

Now let's change the value of the property after creating the object:

user.name = 'eric';

Create a class Student with properties name and age.

ptrudeplsw