Typescript Technical Interview Questions 2024 – Part 1

Typescript Technical Interview Questions

Last Updated On - June 1st, 2024 Published On - Mar 16, 2023

Overview

It’s crucial for developers to comprehend TypeScript’s capabilities as its use in web development is on the rise. In this blog article, we’ll go over a few typical TypeScript technical interview questions that you can encounter when looking for job.

Interview Questions

  1. What is TypeScript and why would you use it instead of plain JavaScript?
  2. Can you explain what Generics are in Typescript? Give an example of how you would use them in your code.
  3. How would you declare a function in TypeScript with optional parameters?
  4. What is the difference between for of And for in Loops?
  5. What is an interface in TypeScript and how would you use it?
  6. Can you explain the difference between “interface” and “type” in Typescript? Give an example of when you would use one over the other.
  7. What is the purpose of the readonly keyword in TypeScript, and how is it used?
  8. What is an Abstract class and how do we implement it?
  9. What is the use of static keywords in TypeScript? Explain with an example.
  10. Write a TypeScript function that takes in an array of numbers and returns the average of those numbers.

Also Read: Coding Challenge: Typescript Technical Interview Questions 2023 – Part 2

Answers

1. What is TypeScript and why would you use it instead of plain JavaScript?

TypeScript is a programming language that is a superset of JavaScript. It adds additional features to JavaScript, such as type annotations, which allow developers to define the type of a variable, function parameter, or return value. TypeScript is designed to make JavaScript development more scalable, maintainable, and reliable.

One of the key benefits of using TypeScript over plain JavaScript is the ability to catch errors during development. Since TypeScript has a type system, it can identify type-related errors at compile-time, rather than at runtime. This can save developers time and effort, as they can catch errors earlier in the development process. See the difference in example.

// Javascript code. Execute without any error

var var12 = 'Hello';
var12 = 12;
console.log(var12);
// Typescript code. This will throw compile time error when you execute it with tsc test.ts

let var12: string = 'Hello';
var12 = 12;
console.log(var12);

2. Can you explain what Generics are in Typescript? Give an example of how you would use them in your code.

Rather than being restricted to a single type, generics in TypeScript allow developers to design reusable code components that may be used with a range of types. Type parameters, which serve as placeholders for later-used specific types, are used to define generics.

Here’s an illustration of how generics can be used in TypeScript:

// Here param1 and param2 are of type number and method genericsex will return output of type number

function genericsex(param1: number, param2: number): number {
    let res = param1 + param2;
    res = res*2;
    return res;
}

console.log(genericsex(2, 4)); // return: 12
console.log(genericsex('Hello', 4)); // Throw compile time error - Argument of type 'string' is not assignable to parameter of type 'number'.

Also Read: Learn MongoDB in 14 Steps: A 10 Minutes Guide


3. How would you declare a function in TypeScript with optional parameters?

// In this example, var2 is the optional parameter to the function optfn

function optfn(var1: number, var2?: string | number) {
    if (var2) {
        console.log(var1);
        console.log(var2)

    } else {
        console.log(var1);
    }
}

optfn(12, 'ABC');

/*
* 12
* ABC
*/

optfn(12); // 12

4. What is the difference between for of And for in Loops?

In TypeScript, the for of and for in loops are used to iterate over collections of data. The main difference between them is the type of the collection they can iterate over.

  1. for of loop:

The for of loop is used to iterate over the values of an iterable object such as an array, a string, or a Map. It allows you to loop through each item in the collection and access its value directly.

//for of Loop

let arr = [10, 21, 32];

for (let val of arr) {
    console.log(val);
}

/*
* 10
* 21
* 32
*/
  1. for in loop:

The for in loop is used to iterate over the properties of an object. It allows you to loop through each property of the object and access its key or value.

//for in Loop

let arr = [10, 21, 32];

for (let val in arr) {
    console.log(val);
}

/*
* 0
* 1
* 2
*/

5. What is an interface in TypeScript and how would you use it?

An interface in TypeScript is a way to define a contract or a set of rules for an object. It describes the properties and methods that an object should have.

  • We can achieve polymorphism by using Interfaces.
  • Interfaces don’t contain any method body, only method signatures are there.
  • Any class that is going to implement an interface must define all method bodies for the method signatures of that interface.
  • Multiple interfaces can be implemented at once in a class.
// Interface declaration

interface Person {
	name: string;
	age: number;
	sayHello(): void;
}

// Interface implementation

class Employee implements Person {
	name: string;
	age: number;
	constructor(name: string, age: number) {
		this.name = name;
 		this.age = age;
	}

 	sayHello() {
	  console.log("Hello, my name is ${this.name} and I'm ${this.age} years old.");
	}
}

let emp = new Employee("John", 30);
emp.sayHello(); // Output: "Hello, my name is John and I'm 30 years old."


Also Read: What is N+1 Query Problem? How do you solve it in Laravel?


6. Can you explain the difference between “interface” and “type” in Typescript? Give an example of when you would use one over the other.

The main difference between “interface” and “type” in Typescript is that an interface is a declaration of the shape of an object, while a type can be used to declare any type of value, including primitive types, unions, and tuples. For example, if you want to define the shape of an object, you would use an interface.

// Interface
interface Person {
  name: string;
  age: number;
}

// Type
const age: number; // Type = number
const name: string; // Type = string
const pin: number | string = 202020;  // Type = union of number and string
let active: boolean = true; // Type = boolean

7. What is the purpose of the readonly keyword in TypeScript, and how is it used?

The readonly keyword in TypeScript is used to indicate that a property should not be modified once it has been initialized. This can be useful for ensuring that certain properties of an object remain constant throughout its lifetime, or for preventing accidental modifications to important data.

interface point {
    readonly x: number,
    readonly y: number
}

If we try to modify a readonly property after it has been initialized, TypeScript will raise an error at compile time. For example:

const points: Interfacesex = {x:2, y:4};
points.x = 3;
console.log(points.x);

// Output: Cannot assign to 'x' because it is a read-only property.

Overall, the readonly keyword can be a useful tool for enforcing immutability and preventing accidental modifications to important data in TypeScript applications.


8. What is an Abstract class and how do we implement it?

An abstract class in Typescript is a class that cannot be instantiated directly but can only be used as a base class for other classes. Abstract classes are useful for defining common behavior or properties that should be shared among multiple subclasses, without implementing the behavior or properties themselves. Subclasses must implement abstract methods or properties in order to be instantiated. Here is an example of an abstract class:

// Abstract Class
export abstract class Area {
    length: number;
    width: number;
    constructor(len: number, width: number) {
        this.length = len;
        this.width = width;
    }

    // Abstract Method
    abstract calculateArea(): number;

    areaOfCircleOfSameLength(){
        return 2*3.14*this.length;
    }
}

// Implementation of abstract class
class RectangleAreaWithCircle extends Area{
    length: number;
    width: number;
    constructor(len,width) {
        super(len,width);
    }

    // Defining method body of abstract method
    calculateArea(): number {
        return this.length*this.width;
    }
    completeAreaWithCircle(): void{
        console.log('Area of rectangle having length = '+this.length+
'cm and width = '+this.width+'cm is = '+this.calculateArea()+
'cmsq AND area of Circle having radius '+this.length+' cm is = '+this.areaOfCircle()+'cmsq');
    }
}

let completeArea = new RectangleAreaWithCircle(10,7);
completeArea.completeAreaWithCircle();

/*Output: Area of rectangle having length = 10cm and width = 7cm is = 70cmsq
 *AND area of Circle having radius 10cm is = 62.800000000000004cmsq
*/


Also Read: Create Short URL Hashing & Tracking Project in 10 Minutes


9. What is the use of static keywords in TypeScript? Explain with an example.

The static keyword is used to define a static property or method on a class. A static property or method is one that belongs to the class itself, rather than to any instance of the class. This means that you can access a static property or method without creating an instance of the class.

class Circle {
  static PI = 3.14; // static property

  // static method
  static calculateArea(radius: number): number { 
    return Circle.PI * radius * radius;
  }
}

console.log(Circle.PI); 
// Output: 3.14

const radius = 5;
const area = Circle.calculateArea(radius);
console.log('The area of a circle with radius'+ radius +' is '+ area);
// Output: The area of a circle with radius 5 is 78.5


10. Write a TypeScript function that takes in an array of numbers and returns the average of those numbers.

Here is the complete code

//Function to calculate average of the input array of numbers
class Calculation{
  average(numbers: number[]): number {
        const sum = numbers.reduce((acc, val) => acc + val, 0);
        return sum / numbers.length;
  }
}

const res = new Calculation();
console.log(res.average([1,3,5,2,11]));
//Output: 4.4

Also Read: Laravel Image Compression Project in 10 Minutes


Conclusion

These are but a few illustrations of the kinds of queries that could be asked in a TypeScript technical interview. It’s crucial to have a firm grasp of the language’s capabilities and features, as well as hands-on experience utilizing TypeScript to resolve actual issues.