EDUCBA

EDUCBA

MENUMENU
  • Explore
    • Lifetime Membership
    • All in One Bundles
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign up
Home Software Development Software Development Tutorials TypeScript Tutorial TypeScript Getter

TypeScript Getter

Updated April 5, 2023

TypeScript Getter

Introduction to TypeScript Getter

TypeScript getter allows the user to have control of access to the properties of the class. This getter method returns the value of the property provided to the class. Also, TypeScript getter is known as an Accessor. This accessor property provides a method to access the class members. Property is the conventional method used for retrieving the variable value. It has one more setter method, also known as a mutator, which will access the class objects and set their values. As a whole, It comes into the picture when the user wants to access any property of the object class, and the TypeScript setter comes into the picture when the user wants to change any property of the object class.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax of TypeScript Getter

Given below is the syntax:

get propertyName() {
// getter code executed to access property using object.
}

The syntax looks similar to that of C# or Java. A getter can be a public, private or protected class.

Let us see how TypeScript getter works with a small example.

Example:

Sample class and how properties are accessed.

Code:

class Employee {
public ID: number;
public name: string;
public designation: string;
}

Here we have a sample Employee class with properties: ID, name and designation. To access this public property of class Employee, we need to create an object for the class Employee, as below.

Code:

let employee = new Employee();

So, the employee is the object created for class Employee. Now, we need to access the property using the object, as below.

Code:

employee.ID = 1024;

In cases if the user assigns any sampleID from the user input/ any type of output, and to perform any pre-checks for ID value before assigning becomes a hectic work to check.

Hence, to avoid checking the validation, TypeScript uses getters that control the access to the class property.

Code:

public get id() {
return this.id;
}
  • We need to change the access modifier for properties from public to private.
  • We need to change the property of the class from id to _id;
  • Getter and setter need to be created for validity check.

Examples of TypeScript Getter

Given below are the examples mentioned:

Example #1

Simple TypeScript getter sample.

Code:

class rectArea {
private _length:number = 5;
private _breadth:number = 2;
private _height:number = 6;
get rectangle() {
return this._length * this._breadth * this._height;
}
}
console.log('Rectangular area is ' + new rectArea().rectangle);

Output:

TypeScript Getter 1

Example #2

TypeScript getter along with setter.

Code:

// @strict: false
class Employee {
private _name: string = "";
get name(): string {
return this._name;
}
set name(nameCheck: string) {
if (nameCheck && nameCheck.length > 8) {
console.log("Name has a max length of " + nameCheck.length);
}
this._name = nameCheck;
}
}
let employee = new Employee();
employee.name = "Karthicks";
if (employee.name) {
console.log(employee.name);
}

Output:

TypeScript Getter 3

Example #3

TypeScript getter with validations.

Code:

class Employee {
private _id: number = 0;
private _name: string = '';
private _designation: string = '';
public get id() {
return this._id;
}
public set id(ID: number) {
if (ID <= 0 || ID >= 200) {
console.log('The ID is invalid');
}
this._id = ID;
}
public get name() {
return this._name;
}
public set name(theName: string) {
if (!theName) {
console.log('Invalid name.');
}
this._name = theName;
}
public get designation() {
return this._designation;
}
public set designation(theDesignation: string) {
if (!theDesignation) {
console.log('Invalid designation.');
}
this._designation = theDesignation;
}
public getFullName(): string {
return `${this.name} ${this.designation}`;
}
}
let employee = new Employee();
employee.id = 1024;
employee.name = 'Benoy';
employee.designation = 'TA';
console.log('These are employee data: Person ' + employee.name + ' with ID ' + employee.id + ' has a designation of ' + employee.designation);

Output:

with validations

It has control over how members are accessed using the class object. These accessors require the user to set the compiler for ECMAScript5 or higher output, which does not support less than ECMAScript5. Accessor with the only getter is assumed to be as read-only. Encapsulation is an important part of OOP and TypeScript. It can be used before a function name and encapsulate the logic, using private properties to manage the state. Data is always protected using TypeScript getter; hence, we can’t change the name but can only get values.

Look at the example below; we will try to change the name.

Example #4

Mutating class property.

Code:

class Student {
stuName;
section;
constructor(sn:string, ssn:string) {
this.stuName = sn;
this.section = ssn;
}
get studentName() {
return this.stuName + " " + this.section;
}
}
var s1 = new Student("John", "Doe");
// Mutating the class property here
s1.studentName = "narayani";
console.log('Student name: ' + s1.studentName);

Output:

Mutating class property

Here, we are trying to change the name of the property, but it won’t work, with the compiler giving an error. To avoid this issue, we should use the TypeScript setter method, which allows us to change the value of the class property. This is a completely separate topic considering the topic seen here.

Conclusion

We have seen what TypeScript getter is and how this getter method is used to access the property value of the class using an object. We have seen the syntax required to be used for the getter method. I looked into few examples that will be useful for handson and have tried mutating the property’s name using getter, which is actually not possible.

Recommended Articles

We hope that this EDUCBA information on “TypeScript Getter” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. TypeScript Functions
  2. TypeScript Operators
  3. TypeScript Array
  4. TypeScript Types
ADVERTISEMENT
All in One Excel VBA Bundle
500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access
ADVERTISEMENT
Financial Analyst Masters Training Program
2000+ Hours of HD Videos
43 Learning Paths
550+ Courses
Verifiable Certificate of Completion
Lifetime Access
ADVERTISEMENT
All in One Data Science Bundle
2000+ Hour of HD Videos
80 Learning Paths
400+ Courses
Verifiable Certificate of Completion
Lifetime Access
ADVERTISEMENT
All in One Software Development Bundle
5000+ Hours of HD Videos
149 Learning Paths
1050+ Courses
Verifiable Certificate of Completion
Lifetime Access
Primary Sidebar
Footer
Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
  • Blog as Guest
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

🚀 Cyber Monday Reloaded Price Drop! All in One Universal Bundle (3700+ Courses) @ 🎁 90% OFF - Ends in ENROLL NOW