TypeScript tutorial: Lesson 13 – Class


Declare classes

Syntax

class class_name { 
   //class scope 
}

A class Declaration can include the following:

  • Properties − A Property is any variable declared in a class. Properties represent data pertaining to objects
  • Constructor − Responsible for allocating memory for the objects of the class
  • Methods − Methods represent actions an object can take.

Example:

class person {
    //properties
    name:string
    //constructor 
    constructor(name:string) { 
        this.name = name 
    }  
    //methods
    set_name(name:string):void {
        this.name = name 
    }
}

After compiling:

"use strict";
var person = /** @class */ (function () {
    //constructor 
    function person(name) {
        this.name = name;
    }
    //methods
    person.prototype.set_name = function (name) {
        this.name = name;
    };
    return person;
}());

Anonymous class

var employee = class {
    name:string
    //constructor 
    constructor(name:string) { 
        this.name = name 
    }  
}

After compiling:

var employee = /** @class */ (function () {
    //constructor 
    function class_1(name) {
        this.name = name;
    }
    return class_1;
}());

Creating Instance objects

Syntax

var object_name = new class_name([ arguments ])

Example:

var employee = new person("Steven")

Accessing Properties and Methods

Syntax:

//accessing an property
obj.property_name 

//accessing a method
obj.method_name(args)

Example:

var employee = new person("Steven")

console.log(employee.name)

employee.set_name("Peter")

console.log(employee.name)

Result:

[LOG]: Steven 
[LOG]: Peter 

Class Inheritance

Syntax

class class_name extends parent_class_name

Example:

class shape {
    //properties
    name:string
    area:number=0
    //constructor 
    constructor(name:string) { 
        this.name = name 
    }  
    //methods
    calcArea():number {    
        return this.area    
    }    
}

class circle extends shape {
    radius:number=0
    setRadius(radius:number){
        this.radius = radius
    }
    //override method
    calcArea():number {     
        return this.area=Math.PI*this.radius**2
    }
}

var c = new circle('circle1')
c.setRadius(10)
console.log(c.calcArea())

Afer compiling:

"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var shape = /** @class */ (function () {
    //constructor 
    function shape(name) {
        this.area = 0;
        this.name = name;
    }
    //methods
    shape.prototype.calcArea = function () {
        return this.area;
    };
    return shape;
}());
var circle = /** @class */ (function (_super) {
    __extends(circle, _super);
    function circle() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.radius = 0;
        return _this;
    }
    circle.prototype.setRadius = function (radius) {
        this.radius = radius;
    };
    //override method
    circle.prototype.calcArea = function () {
        return this.area = Math.PI * Math.pow(this.radius, 2);
    };
    return circle;
}(shape));
var c = new circle('circle1');
c.setRadius(10);
console.log(c.calcArea());
 

Result:

[LOG]: 314.1592653589793 

Method Overriding

In above example, we see method calcArea(), this is an example about Method Overriding.

The super keyword

is used to refer to the immediate parent of a class. The keyword can be used to refer to the super class version of a variable, property or method.

The static Keyword

The static keyword can be applied to the data members of a class. A static variable retains its values till the program finishes execution. Static members are referenced by the class name.

Example:

class staticExample {
    static val:number=0
    static display():void {
        console.log("The value of val is: "+staticExample.val)
    }
}
staticExample.val = 100
staticExample.display()

After compiling:

"use strict";
var staticExample = /** @class */ (function () {
    function staticExample() {
    }
    staticExample.display = function () {
        console.log("The value of val is: " + staticExample.val);
    };
    staticExample.val = 0;
    return staticExample;
}());
staticExample.val = 100;
staticExample.display();
 

Result:

[LOG]: The value of val is: 100 

The instanceof operator

Example:

class A {

}

class B extends A{

}

var b = new B()

console.log("b is an instance of class A: ", b instanceof A)
console.log("b is an instance of class B: ", b instanceof B)

Result:

[LOG]: b is an instance of class A: ,  true 
[LOG]: b is an instance of class B: ,  true 

Access modifiers
TypeScript supports three access modifiers – public, private, and protected.

S.No. Access Specifier & Description
1.

public

A public data member has universal accessibility. Data members in a class are public by default.

2.

private

Private data members are accessible only within the class that defines these members. If an external class member tries to access a private member, the compiler throws an error.

3.

protected

A protected data member is accessible by the members within the same class as that of the former and also by the members of the child classes.

Example:

class A {
    protected val1:string="0"
    private val2:string="val2"
    public val3:number=0
    run():void{
        console.log(this.val2)
    }
}

class B extends A{
    constructor(){
        super()
        this.val1 = "1"
        //this.val2 = "2" //Error: Property 'val2' is private and only accessible within class 'A'.
        this.val3 = 10
    }
}
var b = new B()
//console.log(b.val1) //Error: Property 'val1' is protected and only accessible within class 'A' and its subclasses.
//console.log(b.val2) //Error: Property 'val2' is private and only accessible within class 'A'.
console.log(b.val3)

Result:

[LOG]: 10 

Classe and Interface – The implements keyword

Example:

interface Ishape {
    name:string
    area:number
    calcArea:()=>number

}

class Shape implements Ishape{
    name:string
    area:number=0
    constructor(name:string){
        this.name = name
    }
    calcArea():number{
        return this.area
    }
}

Use Non-null assertion operator in class:

class App extends Vue {
  datetime!:string
  data() {
    return {
      datetime: new Date().toLocaleString()
    }
  }
  mounted() {
    setInterval(() => {
      this.datetime = new Date().toLocaleString()
    }, 1000)
  }
}

1 Comment

Leave a Reply