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 on | public | protect | private |
Class | yes | yes | yes |
Class children | yes | yes | no |
Class instance | no | no | yes |
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
- Add get accessor fullName
- Add only getter for age
- returning firstName + ” ” + lastName
b. Employee Class
- Add incrementSalary method
- Change salary to readonly.
- 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
- Abstract classes are base classes from which other classes may be derived.
- They may not be instantiated directly.
- 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
- how to create ASP.NET Core 3 Web API Project - January 21, 2022
- JWT Authentication using OAUTH - January 10, 2022
- Ado.net database Transactions - January 9, 2022