⊗tsSpOpCM 5 of 37 menu

Class Methods in OOP in TypeScript

Now let's learn how to create class methods. Let's say we have a class User with a property name:

class User { name: string = ''; }

Let's make a method that returns the user name, specifying the return value type:

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

Now let's make a method that changes the value of the name. The name will be passed as a parameter and for this parameter we must also specify the type:

class User { name: string = ''; getName(): string { return this.name; } setName(name: string): void { this.name = name; } }

Create a class Student with properties name and age. Add methods to get and change these properties.

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