⊗tsSpOpCCo 6 of 37 menu

Class Constructor in OOP in TypeScript

Let's pass the initial value of the property as a parameter of the class constructor. In this case, the parameter also needs to be given a type:

class User { name: string = ''; constructor(name: string) { this.name = name; } }

There is a nuance here. Since the property value is assigned in the constructor, the initial value of the property can be omitted and this will not be an error:

class User { name: string; // do not set the value of constructor(name: string) { this.name = name; } }

Let's now create an object of our class, immediately specifying its name:

let user: User = new User('john');

Let's look at the property of our class:

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

Create a class Employee, into the constructor of which pass the first name, last name, age and salary of the employee.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline