Access Modifiers in Typescript

Access Modifiers in Typescript

Typescript supports public, private, and protected access modifiers to your methods and properties. By default, if access modifiers are not given the method or property is considered as public, and they will be easily accessible from the object of the class.

In case of private access modifiers, they are not available to be accessed from the object of the class and meant to be used inside the class only. They are not available for the inherited class.

In case of protected access modifiers, they are meant to be used inside the class and the inherited class and will not be accessible from the object of the class.

Example:

class Person {
    protected name: string;
    protected age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }

    private getName(): string {
        return this.name;
    }

    getDetails(): string {
        return "Name is "+ this.getName();
    }
}

class Student extends Person {
    tmarks: number;
    constructor(name: string, age: number, tmarks: number) {
        super(name, age);  
        this.tmarks = tmarks;    
    }
    getMarks(): number {
        return this.tmarks;
    }

    getFullName(): string {
        return this.name;
    }
    
    setMarks(tmarks) {
        this.tmarks = tmarks;
    }
}

let _std1 = new Student('Sheena', 24, 500);
_std1.getMarks(); // output is 500
_std1.getFullName(); // output is Sheena
_std1.getDetails(); // output is Name is Sheena
  • Private properties or methods cannot be accessed by the object of the class and also the derived class, they are meant to be used internally inside the class.
  • Protected properties and methods also cannot be accessed by the object created. They are accessible from inside the class and available to the class extending it.
  • Public properties and methods are declared without any keyword. They are easily accessed using the object of the class from outside.

Interface in TypeScript

One of the core features of Typescript is interfaces. The interface is a set of a rule defined which needs to be implemented by the entity using it. The entity can be a class, function, or variable. An interface can be made up of properties and methods. You can define properties as optional using “?” syntax for that property or method. The interface adds a strong type check for any function, variable, or class implementing the interface.

Syntax of an interface in Typescript:

interface Dimension {
    width: string;
    height: string;
}

You have defined an interface named as Dimension which has properties width and height, and both have type as a string.

Now this interface can be implemented by a variable, a function, or a class. Here is the example of variable implementing the interface Dimension.

Example:

interface Dimension {
    width: string;
    height: string;
}

let _imagedim: Dimension = {
    width: "100px",
    height: "200px"
};

The signature of the interface Dimension has width and height, and both are mandatory. In case while implementing the interface, any of the property is missed, or the type is changed, it will give a compile time error while compiling the code to javascript.

The above code, when compiled to javascript, looks as follows:

var _imagedim = {
    width: "100px",
    height: "200px"
};

Let us now see how to use an interface with a function.

Using Interface on a function as a return type

Example:

interface Dimension {
    width: string;
    height: string;
}

function getDimension() : Dimension {
    let width = "300px";
    let height = "250px";
    return {
        width: width,
        height: height
    }
}

In the above example, the interface Dimension is implemented on the function getDimension() as the return type. The return type of getDimension() has to match with the properties and type mentioned for Interface Dimension.

The compiled code to Javascript will be as follows:

function getDimension() {
    var width = "300px";
    var height = "250px";
    return {
        width: width,
        height: height
    };
}

During compilation, if the return type does not match with the interface, it will throw an error.

Interface as function parameter

interface Dimension {
    width: string;
    height: string;
}

function getDimension(dim: Dimension) : string {
    let finaldim  = dim.width +"-"+ dim.height;
    return finaldim;
}

getDimension({width:"300px", height:"250px"}); // will get "300px-250px" 

So above example, you have used Interface Dimension as a parameter to the function getDimension(). When you call the function, you need to make sure the parameter passed to it matches to the Interface rule defined.

The compiled code to Javascript will be as follows:

function getDimension(dim) {
    var finaldim = dim.width + "-" + dim.height;
    return finaldim;
}
getDimension({ width: "300px", height: "250px" });

Class implementing Interface

To make use of interface with a class, you need to use the keyword implements.

Syntax for Class implementing an interface:

class NameofClass implements InterfaceName {
}

Following example shows working of interface with class.

interface Dimension {
    width : string,
    height: string,
    getWidth(): string; 
}

class Shapes implements Dimension {
    width: string;
    height: string;
    constructor (width:string, height:string) {
        this.width = width;
        this.height = height;
    }
    getWidth() {
        return this.width;
    }
}

In the above example, you have defined interface Dimension with properties width and height both of type string and a method called getWidth() which has return value as a string.

The compiled code to Javascript will be as follows:

var Shapes = /** @class */ (function () {
    function Shapes(width, height) {
        this.width = width;
        this.height = height;
    }
    Shapes.prototype.getWidth = function () {
        return this.width;
    };
    return Shapes;
}());

Functions in Typescript

Functions are set of instructions performed to carry out a task. In Javascript, most of the code is written in the form of functions and plays a major role. In typescript, you have class, interfaces, modules, namespaces available, but still, functions play an important role. The difference between the function in javascript and typescript function is the return type available with typescript function.

JavaScript function:

function add (a1, b1) { 
   return a1+b1;
}

Typescript function:

function  add(a1 : number, b1: number) : number {
    return a1 + b1;
}

In the above functions, the name of the function is added, the params are a1, and b1 both have a type as a number, and the return type is also a number. If you happen to pass a string to the function, it will throw a compile-time error while compiling it to JavaScript.

Making call to the function: add

let  x = add(5, 10) ;  // will return 15
let  b = add(5); // will throw an error : error TS2554: Expected 2 arguments, but got 1.
let c = add(3,4,5); // will throw an error : error TS2554: Expected 2 arguments, but got 3.
let t = add("Harry", "John");// will throw an error :  error TS2345: Argument of type '"Harry"' is not assignable to parameter of type 'number'.

The params a1 and b1 are mandatory parameters and will throw an error if not received in that manner. Also, the param type and return type is very important and cannot change once defined.

Optional parameters to a function

In javascript, all the parameters to the functions are optional and considered as undefined if not passed. But same is not the case with typescript, once you define the params you need to send them too, but in case you want to keep any param optional, you can do so by using? against the param name as shown below:

function getName(firstname: string, lastname?: string): string {
    return firstname + lastname;
}

let a = getName("John"); // will return Johnundefined.
let b = getName("John", "Harry"); // will return JohnHarry
let c = getName("John", "H", "Harry"); // error TS2554: Expected 1-2 arguments, but got 3.

Please note that the optional params are to be defined in a function at the last only, you cannot have the first param as optional and second param as mandatory.When you call the function with one param compiler will throw an error. So it is necessary to keep the optional params at the end.

Assign Default Values to Params

You can assign default values to params as shown below:

function getName(firstname: string, lastname = "Harry"): string {
    return firstname + lastname;
}

let a = getName("John"); // will return JohnHarry
let b = getName("John", "H"); // will return JohnH

Similar to optional params, here too default initialized params has to be kept at the end in a function.

Rest Parameters

You have seen how typescript handles mandatory params, optional params, and the default value initialized params. Now, will take a look at rest params. Rest params are a group of optional params defined together, and they are defined using three dots (…) followed by the name of the param, which is an array.

Syntax for Rest params:

function testFunc(a: string, ...arr: string[]) :string {
    return a + arr.join("");
}

As shown above, the rest params are defined using (…param-name); the rest param is an array prefixed by three dots. The array will have all the params passed to it. You can call the function, as shown in the example below:

Example:

let a = testFunc("Monday", "Tuesday", "Wednesday", "Thursday"); // will get output as MondayTuesdayWednesdayThursday

Arrow Functions

An arrow function is one of the important features released in ES6, and it is available in typescript too. Arrow function syntax has a fat arrow in it due to which the function is called an arrow function.

Arrow function Syntax:

var nameoffunction = (params) => {				
 // code here			
}

About Author

Leave a Reply

Your email address will not be published. Required fields are marked *

PAGE TOP
error

Enjoy this blog? Please spread the word :)

RSS
Follow by Email