EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials TypeScript Tutorial TypeScript Getter
Secondary Sidebar
TypeScript Tutorial
  • TypeScript Basic and Advanced
    • What is TypeScript?
    • Typescript Examples
    • TypeScript Versions
    • TypeScript Operators
    • JavaScript dump object
    • JavaScript get Method
    • Webpack ReactJS
    • Code Generator JavaScript
    • JavaScript Projects
    • Call Stack JavaScript
    • JavaScript Projects GitHub
    • JavaScript Filter Function
    • JavaScript nan
    • JavaScripttimestamp
    • TypeScript loop
    • CoffeeScript
    • TypeScript Webpack
    • setTimeout TypeScript
    • DHTMLX
    • CoffeeScript for loop
    • TypeScript number
    • JavaScript export module
    • TypeScript string contains
    • TypeScript Inheritance
    • TypeScript get
    • TypeScript undefined
    • TypeScript Global Variable
    • TypeScript Dictionary
    • TypeScript Generic
    • TypeScript Cast Object
    • TypeScript Optional Parameters
    • TypeScript? switch
    • TypeScript promise
    • TypeScript tuple
    • TypeScript Hashmap
    • TypeScript let
    • TypeScript Getter
    • TypeScript Pattern Matching
    • TypeScript number to string
    • TypeScript substring
    • TypeScript?lambda
    • TypeScript UUID
    • TypeScript JSDoc
    • TypeScript Decorators
    • Typescript for loop
    • TypeScript HTTP Request
    • TypeScript Abstract Class
    • TypeScript Question Mark
    • TypeScript Nullable
    • TypeScript reduce
    • TypeScript Mixins
    • TypeScript keyof
    • TypeScript string to number
    • TypeScript JSON parse
    • TypeScript const
    • TypeScript declare module
    • TypeScript String
    • TypeScript filter
    • TypeScript Multiple Constructors
    • TypeScript? Set
    • TypeScript string interpolation
    • TypeScript instanceof
    • TypeScript JSON
    • TypeScript Arrow Function
    • TypeScript generator
    • TypeScript namespace
    • TypeScript default parameter
    • TypeScript cast
    • TypeScript babel
    • Typescript Key-Value Pair
    • TypeScript if
    • TypeScript keyof Enum
    • TypeScript wait
    • TypeScript Optional Chaining
    • TypeScript JSX
    • TypeScript Version Check
    • TypeScript Unit Testing
    • TypeScript Handbook
    • TypeScript module
    • TypeScript Extend Interface
    • TypeScript npm
    • TypeScript pick
    • TypeScript Interface Default Value
    • JavaScript import module
    • Obfuscate Javascript
    • TypeScript basics
    • setInterval TypeScript
  • Type of Union
    • TypeScript Object Type
    • TypeScript type check
    • TypeScript promise type
    • TypeScript JSON type
    • TypeScript Union Types
    • TypeScript typeof
    • TypeScript Types
  • TypeScript Array
    • TypeScript Array of Objects
    • Methods TypeScript Array
    • TypeScript remove item from array
    • TypeScript add to array
    • TypeScript Array Contains
  • Function Of Array
    • TypeScript Function Interface
    • TypeScript Functions
    • TypeScript Export Function
    • TypeScript function return type

TypeScript Getter

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.

Syntax of TypeScript Getter

Given below is the syntax:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

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

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

Let’s Get Started

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

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?

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

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