Top 30 TypeScript Interview Questions


💡 What is Typescript?

Typescript is an Open source programming language developed by Microsoft. Typescript is superset of JavaScript and it is a strict type checking language.
Because it is a superset of JavaScript, every JavaScript program is a valid typescript program as well. It is designed for large applications and when typescript comes to the browser it compiles to JavaScript. Same as other languages like java and dot net, typescript supports the OOPS concept very clearly. It has the class, interface, abstract classes, public, private, protected members, static members, etc.


💡 What is Class & Interface?

In Vanilla Javascript or Traditional javascript, Function works like a class. By using a prototype we implement Inheritance. IN ES6, Javascript builds an application using an Object-oriented class-based approach by keyword ‘Class’.

class ClassA {
    myName: string;
    constructor(name: string) {
        this.myName = name;
   }
}

Typescript is called static typing language means it strongly depends on type-checking. The interface plays this role in typescript to check the shape of the object or define the type of object’s properties.

interface IEmp {
    name : string;
    empId:number;
}
var employee = {} as IEmp;


💡 What is public, private, and Protected?

In TypeScript, each member is public by default. A member which is declared using public can be accessed throughout the Class.
When a member is marked as private, it cannot be accessed from outside of its containing class.
Protected works mostly as a private member but with a difference that When a member is declared as protected, can also be accessed within deriving classes.

class Person {
    name: string; // public member by default
    public fatherName; string // public member
    private personId: number; // private member
    protected address: string; // protected member
    contructor() {
    }
}


💡 What are all types available in typescript?

Boolean, Number, String, Array, Tuple, Enum, Any, Void, Null and Undefined, Never, Object


💡 What is the difference between null and undefined types?

In Typescript null and undefined values have their own types respectively null and undefined.

let  a: undefined = undefined;
let b: null =  null;


💡 What is tuple type and never type?

Tuple types are used to express an array with a fixed number of elements.

var emp: [number, string, string]; // here we have defined emp variable with three fixed properties.
emp = [1, 'jsmount', 'India'];

never — never is a return type of a function expression that always throws an exception or a type which never returns.

function infiniteLoop(): never {
    while(true) {}
}
function throwException(e: string): never {
    throw new Error(e);
}


💡 What is Nullish Coalescing operator in Typescript?

Nullish Coalescing Operator is newly introduced in typescript 3.7 and it is written with the symbol ‘??’.

 var a = 'jsmount'; var b = 'Java';
 var c = a ?? b;

This is a new way to say that the value of a will be used when it’s “present” but when it is ‘null’ or ‘undefined’, use value of b;


💡 What is destructuring, Tuple destructuring, Object destructuring?

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Array destructuring

var values = [1, 2];
var [first, second] = values;
console.log(first); // outputs 1
console.log(second); // outputs 2
var [a, b, c] = values;
console.log(c); // ouput undefined -- will not raise any error here.

Tuple destructuring

This is works mostly the same as array destructuring. In this, destructuring variables also get the types of the corresponding tuple elements.

var tuple: [number, string, number] = [1, 'jsmount', 2];
var [first, second, third] = tuple;
var [a, b, c, d] = tuple; // it will raise an Error because no element at index 3 but in Array dest. it will be undefined.

Object destructuring

var obj = {a: 1, b: 2, c: 3};
var {a, b} = obj;

This creates new variables a and b from obj.a and obj.b. Notice that you can skip c if you don’t need it.


💡 What is a spread operator? Give some examples to use it?

The spread operator is used to spread or expand an array to another array or an object to another object.

let a = [1, 2];
let b = [3, 4];
let c = [0, …a, …b, 5]; // output > [0, 1, 2, 3, 4, 5]
var obj1 = {a: 1, b: 2, c: 3};
var obj2 =  {…obj1, c: 5}; // output > {a: 1, b: 2, c: 5}
var arr = [4,5,6,7];
var arr2 = […arr]; // it creates a copy of arr. output > [4,5,6,7] 

We can also use the spread operator instead of apply method.

var arr = [2, 3, 4];
Math.max.apply(null, arr); // output > 4
Math.max(…arr); // output > 4


💡 Does TypeScript support function overloading?

TypeScript provides the concept of function overloading. We can create multiple functions with the same and different property types and return types.
But keep in mind, the number of parameters should be the same.

function printMe(x: string, y: string): string;

function printMe(x: number, y: number) : number;

// Most importtant thing is that, this function with any type will receive only string or numbers as mentioned the above declaration.

function printMe(x: any, y: any): any {
  console.log(x + y);
}

**Run program**

// properties type are number
printMe(10, 20);

// properties type are string
printMe('Js', 'Mount');

// Not valid. It will throw a compile error.
printMe('Js', 07);


💡 What are Generics in TypeScript?

Generics provides a way to create components that work with any data type and not only restricted to a particular data type. It is similar to other programming languages like Java and c#.
There is a special kind of variable to represent Generics and that is <T>.

Syntax:

function identity<T>(arg: T): T {
  return arg;
}

 // If you are working with Array, you can write this like - 

function identity<T>(arg: T[]): T[] {
  // here you can use array methods
  return arg;
}
function callMe<T>(arg: T): T {
  return arg;
}

callMe<number>(12); // valid
callMe<number>('Mohit'); // invalid - Argument of type 'string' is not assignable to parameter of type 'number'.


function fun<T>(arg: Array<T>): T[] {
  console.log(arg.length); // valid statement
   return new Array<T>().concat(arg);
}

fun<number>([1,2,3]); // valid
fun<string>(['A', 'B']); // valid

fun<number>([1, 'A']); // invalid - Type 'string' is not assignable to type 'number'.

Why not use ‘any’ here?

If we use any, we can pass any type of data to our functions. However, this may not be the desired behavior. So data should be consistent as per its data type.
Check our code example function ‘fun‘ that we can pass only numbers to number array or string to string array. We can not supply numbers to the string array. That is the beauty of Generics.


💡 Explain Generic Constraints?

When we declare a type parameter that is constrained by another type parameter so it is called Generic Constraints.

class Employee {
  empName: string;
  constructor(name: string) {
    this.empName = name;
  }
}

function getEmployee<T extends Employee>(arg: T): string {
  return arg.empName;
}

getEmployee(new Employee('Harry')); // valid

const jack  = {
    code: 343
}

getEmployee(jack); 
// invalid - argument of type '{ code: number; }' is not assignable to 
// parameter of type 'Employee'.  Property 'empName' is missing in type 

getEmployee({empName: 12345}) // invalid

getEmployee({empName: 'John'}) // valid

In the above example, the getEmployee function is a generic function with constraints of Class Employee.


💡 Commonly asked interview question – setTimeout inside for loop? Explanations.

for (var i = 0; i < 10; i++) {
    setTimeout(function() { console.log(i); }, 100 * i);
}
// output > 10 (10 times) but we were expecting its output >  1 to 10. 

Let’s see what is happening here. setTimeout will execute a function after some milliseconds, but only after the for loop has stopped executing; By that time the for loop has stopped executing, the value of i is 10. So each time the given function gets called, it will print out 10!.

Solution:

BY Using IIFE – Immediately Invoked Function Expression

for (var i = 0; i < 10; i++) {
// capture the current state of 'i' by invoking a function with its current value
 (function(i) {
     setTimeout(function() { console.log(i); }, 100 * i);
     })(i);
 }


By Using let keyword;

for (let i = 0; i < 10 ; i++) {
    setTimeout(function() { console.log(i); }, 100 * i);
}
output > 1 to 10 (wowww.. much easy with 'let')

let works with lexical scoping means with each iteration it creates a new scope.


💡 What is the interface? How do we add optional & read-only properties?

Interface is a thing that gives a shape to an object and used to type checking. By using ‘?’ we can create optional properties. And with ‘readonly‘ keyword we can create read-only properties.

interface Point {
    readonly x: number;
    readonly y: number;
    startX? : number;
    startY? : number;
}


💡 What is the difference between read-only and const?

Where we have to use read-only or const it totally depends on whether you’re using it on a variable or a property. Variables use const whereas properties use read-only.


💡 How can we add extra properties in an object if not defined in its interface?

When an object can have some pre-known properties but could also have any number of other properties. So we can create an interface like the below structure:

interface SquareConfig {
     color?: string;
     width?: number;
     [propName: string]: any;
 }
var square : SquareConfig;
square.color = 'red';
square.height = '100'; // it will work here.


💡 How a Class Implements an Interface?

interface ClockInterface {
     currentTime: Date;
     setTime(d: Date): void;
 }
class Clock implements ClockInterface {
     currentTime: Date = new Date();
     setTime(d: Date) {
         this.currentTime = d;
     };
     constructor(h: number, m: number) { }
 }


💡 How we extends interfaces?

interface DrawOption {
     shapeName: string;
     color: string;
 }
interface LineDrawOption extends DrawOption {
     lineLength: number;
 }
let line = {} as LineDrawOption;
line.color = 'red';
line.shapeName = 'Line';
line.lineLength = 20;


💡 What is super() keyword?

A derived class that contains a constructor function must call super() which will execute the constructor of the base class. What’s more, before we ever access a property on this in a constructor body, we have to call super(). This is an important rule that TypeScript will enforce.
So basically when we extends a class into another class that have constructor function so it calls super() to execute constructor function of base class.

class Person {
     fullName: string;
     constructor(name: string) {
         this.fullName = name;
     }
 }
class JSMount extends Person {
     constructor(name: string) {
         super(name);
     }
 }
var js = new JSMount('MS');
console.log(js.fullName); // output > MS


💡 What is accessors get set?

TypeScript supports getters/setters to access a member of an object. This gives you a way to implement security to control over how a member is accessed on each object.
To implement accessors we use get / set.

class Technology {
     techName: string;
 }
var tech = new Technology();
tech.techName = 'JavaScript';

So here we can add any string value in techName property. To provide some validations on this we use get / set;

class Technology {
    private _techName: string;

    get() {
        return this._techName;
    }
    set(techName: string) {
        if (techName && techName.length> 4){
            this._techName = techName;
        }
        
    }
}
var tech1 = new Technology();
tech1.set('Java');
tech1.get();


💡 What is Static properties in a Class?

We can also create static member of a class. Static member are visible on the class itself rather than on its instances.

class Spider {
    static speed: number;
    move(unit: string) {
        return `Spider man can move with ${Spider.speed} ${unit} per hours speed`;
    }
}
var s = new Spider();
s.move('KM');

class SpriderMan extends Spider {
    constructor() {
        super();
    }
    flySpeed() {
        return Spider.speed;
    }
}


💡 What is abstract Class? Why we use it?

The abstract keyword is used to define abstract classes as well as abstract methods within an abstract class. These are base classes from which other classes may be derived. Methods within an abstract class that are marked as abstract do not contain an implementation and must be implemented in derived classes.

abstract class Doctor {
     abstract getDoctorAddress(add: string): void;
     getDoctorId() {
         return '23232432';
     }
 }
class Hospital extends Doctor {
     getDoctorAddress(add: string) {
         return 'This is doctor address ' + add;
     }
 }

Typescript Basic Interview Questions…


💡 Can a interface extends a Class?

When we create a class, it actually create two things – a type representing instances of the class and a constructor function. Because classes create types, you can use them in the same places you would be able to use interfaces.

class Coordinate {
    x: number;
    y: number;
}

interface Coordinate3D extends Coordinate{
    z: number;
}

var shape : Coordinate3D;
shape.x = 123;


💡 What is Rest parameter?

Let’s understand first the type of parameters so we have the required parameters, default parameters and optional parameters. One thing is common in these parameters are they talk about only single parameter at a time. On the other side we have rest parameter as well that is used to pass multiple parameters as a group at once. With the rest parameter we can pass any number of optional parameters.

If we have a function where some of the parameters is required but sometimes you may not know how many parameters a function will ultimately take. In traditional JavaScript we use arguments variable to catch all the parameters in the function body but with the ES6 we can use the rest parameter to work upon these.

function buildProfile(id: number, name: string, ...restData : String[]) {
    return id + ' ' + name + ' ' + restData.join(' ');
} 

let profile1 = buildProfile(1, 'MS', 'Java', 'Experience 5 years');


Read here for more details about class in Typescript:
http://www.typescriptlang.org/docs/handbook/classes.html

Read here for JavaScript Interview questions:
https://www.jsmount.com/javascript-interview-questions-answers-for-experienced-part-2/

Top 30 TypeScript Interview Questions

Leave a Reply

Your email address will not be published.