⊗tsSpOpAcs 13 of 37 menu

Accessors in OOP in TypeScript

Just like in pure JavaScript, in TypeScript you can make accessors properties: getters and setters.

In TypeScript, however, accessor names should not match property names. Let's see in practice. Let's make accessors for a private property name. If we also give accessor names name, then the following code will return an error:

class User { private name: string = ''; public set name(name: string) { // will give an error this.name = name; } public get name(): string { return this.name; } }

Let's fix the problem, for example, by renaming the private property:

class User { private _name: string = ''; public set name(name: string) { this._name = name; } public get name(): string { return this._name; } }

Make a class User containing private properties with name and age. Make accessors of these properties.

Modify the age setter to accept ages between 0 and 120. If any other value is specified, an exception should be thrown.

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