typescript class types and and oops concepts

Updated : Nov 13, 2019 in Articles

oops concepts in typescript with examples

In this article we will learn about oops concepts in typescript with examples like, methods, Properties, casting and Type Assertion, abstract class, interface class

Working with Classes in typescript

JavaScript programmers were able to build their applications using this object-oriented class-based approach.

TypeScript allow developers to use these techniques now, and compile them down to JavaScript that works across all major browsers and platforms, without having to wait for the next version of JavaScript.

before going to read this article you will go through types of functions and parameters in typescript

  • Person class with following members:
    1. Fields: firstName, lastName, dateOfBirth,
    2. constructor,
    3. Methods: greetmessage, Introduction.
class Person {

       firstName: string
       lastName: string
       dateOfBirth: Date

  constructor(fn: string, ln: string, dateOfBirth: Date) {
        this.firstName = fn;
        this.lastName = ln;
        this.dateOfBirth = dateOfBirth;
}

greetmessage(friendName: string): string {
return "Hello " + friendName + ", how are you doing?";
}

Introdution(): string {

let age = (new Date().getFullYear() - this.dateOfBirth.getFullYear())
return "Hello, I am " + this.firstName + " " + this.lastName + " and I am " + age + "yrs old";

}

}

Note: “this” is compulsory for every member when used inside a method.

Using Class:

let person: Person = new Person("vijay", "supraja");

alert(person.greet("son vikas"));

constructor and properties

class Person {

    constructor(private firstName: string, private lastName: string) {
    
    }
}

the above one Is same as

class Person {

      private firstName: string;
      private lastName: string;

      constructor(fn: string, ln: string) {
          this.firstName = fn;
          this.lastName = ln;
         }
}

Inheritance class in typescript

Inheritance: The following example demonstrates:

Extending class in typescript

  • Class Employee in extended/inherited from Person
    a.Fields: department, salary
    b. Constructor MUST call Parent class constructor.
class Employee extends Person {

       DepartmentName: string
       salary: number

constructor(fn: string, ln: string, dateOfBirth: Date, deptName: string, sal: number) {
            super(fn, ln, dateOfBirth);
            this.DepartmentName = deptName;
            this.salary = sal;

}
}

Note: Every Child class constructor must call Parent class constructor using super.

Method overriding and super to call parent class method.

Override self-Introduction

Introdution(): string {

var s: string = super.selfIntrodution()
return s + " working in " + this._departmentName + " department";

}

Access Specifiers in typescript

Public, private and protected, read-only modifiers

Accessed onpublicprotectprivate
Classyesyesyes
Class childrenyesyesno
Class instancenonoyes

By default all members are public,Person class: Change firstName and lastName to private. Change dateOfBirth as protected Change dateOfBirth as readonly. Readonly Members can be initialized in constructor only.

Get and set Accessors in typescript follow the given below example

a. Person class

  1. Add get accessor fullName
  2. Add only getter for age
  3. returning firstName + ” ” + lastName

b. Employee Class

  1. Add incrementSalary method
  2. Change salary to readonly.
  3. Validate departmentName not to allow “”
class Person {

      protected firstName: string
      protected lastName: string
      private readonly dateOfBirth: Date

      public get fullName(): string {
      return this.firstName + this.lastName;
}

public get age(): number {
return (new Date().getFullYear() - this.dateOfBirth.getFullYear());
}

constructor(fn: string, ln: string, dateOfBirth: Date) {
this.firstName = fn;
this.lastName = ln;
this.dateOfBirth = dateOfBirth;
}

greet(friendName: string): string {
return "Hello " + friendName + ", how are you doing?";
}

Introdution(): string {
let age = (new Date().getFullYear() - this.dateOfBirth.getFullYear())
return "Hello, I am " + this.firstName + " " + this.lastName + " and I am " + age + "yrs old";
}

}



class Employee extends Person {

         private _departmentName: string
         private _salary: number

constructor(fn: string, ln: string, dateOfBirth: Date, deptName: string, sal: number) {
super(fn, ln, dateOfBirth);
this._departmentName = deptName;
this._salary = sal;
}

//Method overriding
selfIntrodution(): string {
var s: string = super.selfIntrodution()
return s + " working in " + this._departmentName + " department";
}

public incrementSalary(amount: number) {
this._salary += amount;
}

public get salary(): number {
return this._salary;
}

public get departmentName(): string {
return this._departmentName
}

public set departmentName(newValue: string) {
if (newValue == "")
throw "Department cannot be null";
this._departmentName = newValue;
}

}

Type casting in typescript

Use < > or as keyword for casting. Since Typescript 1.6, the default is as because < > is ambiguous in .jsx files. Using Instanceof you can find out the type of any object, similarly using typeof you can find out the type of a variable.

 var obj0: string;
 var obj1: any;
 obj1 = obj1; // using <>
 obj1 = obj1 as string; // using as keyword
let person: Person
person = empobj;
empobj = <Employee>person;

Type Assertion in type script

Overriding / customizing the types of typescript in any way you want to do is known as Type Assertion mechanism.Here is the reason why we are choosing for Type Assertion.

Javascript / typescript does not allow to create dynamic properties to any object i.e. we cannot expand the properties in any object dynamically

var user = {};
user.firstName = "Hellosupraja" //Error: property firstName does not exist on type {}

We can fix this simply by using type assertion as IUser

interface IUser {

userId: number;
userName: string;

}
var user = {} as IUser;
user.userId = 123;
user.userName = 'hello';

Here the compiler will provides autocomplete for the object properties.

var user = <IUser>{
//compiler will provide autocomplete for properties of IUser
};

Static Properties in typescript

a. Must be accessed using class name.
b. Add MaxSalary as static member
c. Change incrementSalary to validate new salary.

Edit class Employee

public static MaxSalary: number;

public incrementSalary(amount: number) {

if (this._salary + amount > Employee.MaxSalary)
throw "Salary cannot be greater than " + Employee.MaxSalary;
this._salary += amount;

}

Abstract class in typescript

  1. Abstract classes are base classes from which other classes may be derived.
  2. They may not be instantiated directly.
  3. An abstract class may contain implementation details for its members.
abstract class Figure
{
      protected Dimension: number
      public abstract Area(): number
}
class Circle extends Figure
{
     constructor(radius: number) {
     super();
     this.Dimension = radius;
}

public Area(): number {
      return Math.PI * this.Dimension * this.Dimension;
  }
}

class Square extends Figure {
     constructor(side: number) {
     super();
     this.Dimension = side;
}

public Area(): number {
    return this.Dimension * this.Dimension;
}
}

var fig: Figure = new Circle(10); //new Square(10);
alert(fig.Area());

Summary

In this article we will learned basic concepts of typescript class types and oops concepts

Latest posts by DuttaluruVijayakumar (see all)
Like
Like Love Haha Wow Sad Angry
15

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x