# TypeScript Interview Questions for Developers

Use our engineer-created questions to interview and hire the most qualified TypeScript developers for your organization.

## TypeScript

TypeScript is popular choice for companies that value the web development prowess of JavaScript but wanted the security and error prevention that comes with added type safety.

> According to the [CoderPad 2024 Developer survey](/content/blog/hiring-developers/top-10-in-demand-programming-languages/index.html), TypeScript is the 7th most in-demand language among technical recruiters and hiring managers.

In order to assess the TypeScript proficiency of developers in coding interviews, we have supplied practical coding tasks and interview queries below. Furthermore, we have delineated a collection of recommended guidelines to guarantee that your interview inquiries effectively gauge the candidates’ TypeScript capabilities.

## TypeScript example question

### Help us design a parking lot

Goals: Design a parking lot using object-oriented principles.

#### Here are a few methods that you should be able to run:

- Tell us how many spots are remaining
- Tell us how many total spots are in the parking lot
- Tell us when the parking lot is full
- Tell us when the parking lot is empty
- Tell us when certain spots are full e.g. when all motorcycle spots are taken
- Tell us how many spots vans are taking up

**Assumptions:**

- The parking lot can hold motorcycles, cars and vans
- The parking lot has motorcycle spots, car spots and large spots
- A motorcycle can park in any spot
- A car can park in a single compact spot, or a regular spot
- A van can park, but it will take up 3 regular spots

### Junior TypeScript interview questions

**Question:** Explain what TypeScript is and how it differs from JavaScript. Provide an example of a TypeScript feature that is not available in JavaScript.

**Answer:** TypeScript is a statically typed superset of JavaScript developed by Microsoft. It adds optional static type-checking to JavaScript, allowing developers to define types for variables, function parameters, and return values. The TypeScript code is then compiled to plain JavaScript, which can be executed in any JavaScript runtime.

One of the key differences between TypeScript and JavaScript is the type system. In TypeScript, you can explicitly specify the types of variables and function signatures, which enables catching type-related errors during development and provides better tooling support, such as code completion and type inference.

Example:
```javascript
// TypeScript
function add(a: number, b: number): number {
  return a + b;
}
```

In this TypeScript example, the function `add()` explicitly declares the types of its parameters `a` and `b` as `number`, as well as its return type as `number`. This helps catch potential type errors during development.

In JavaScript, there is no built-in support for static types, so you would write the same function without type annotations:
```javascript
// JavaScript
function add(a, b) {
  return a + b;
}
```

**Question:** The following TypeScript code is intended to implement a class representing a circle. However, it contains a syntax error and doesn’t compile. Identify the error and fix the code.

```javascript
class Circle {
  private radius: number;

constructor(radius) {
    this.radius = radius;
  }

calculateArea() {
    return Math.PI * radius * radius;
  }
}

const circle = new Circle(5);
console.log(circle.calculateArea());
```
**Answer:** The error in the code is that the variable `radius` in the `calculateArea()` method is not accessed correctly. It should be accessed using `this.radius` to refer to the class property.

```javascript
class Circle {
  private radius: number;

constructor(radius: number) {
    this.radius = radius;
  }

calculateArea() {
    return Math.PI * this.radius * this.radius;
  }
}

const circle = new Circle(5);
console.log(circle.calculateArea());
```

**Question:** Explain the concept of interfaces in TypeScript and provide an example of how they can be used.
**Answer:** Interfaces in TypeScript are used to define the structure of objects or classes. They describe the shape of an object, specifying the names of its properties and their corresponding types.

Example:
```javascript
interface Person {
  firstName: string;
  lastName: string;
  age: number;
  greet: () => void;
}

class Employee implements Person {
  firstName: string;
  lastName: string;
  age: number;

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

greet() {
    console.log(`Hello, my name is ${this.firstName} ${this.lastName}.`);
  }
}

const employee = new Employee("John", "Doe", 30);
employee.greet();
```
In this example, we define an interface `Person`, specifying the properties `firstName`, `lastName`, `age`, and a function `greet()`. Then, we create a class `Employee` that implements the `Person` interface, ensuring that it has all the required properties and methods defined in the interface.

**Question:** The following TypeScript code is intended to create an array of numbers and then filter the even numbers from it. However, it contains a logical error and doesn’t produce the correct result. Identify the error and fix the code.

```javascript
const numbers: number[] = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter((num) => num % 2);
console.log(evenNumbers);
```
**Answer:** The logical error in the code is the condition inside the `filter()` method. The condition should check for equality to 0 to correctly filter even numbers.

```javascript
const numbers: number[] = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter((num) => num % 2 === 0);
console.log(evenNumbers);
```

In this corrected code, the `filter()` method correctly filters the even numbers from the `numbers` array using the condition `num % 2 === 0`.

**Question:** Explain the concept of generics in TypeScript and provide an example of how they can be used.
**Answer:** Generics in TypeScript allow us to create reusable components that can work with different types while preserving type safety. They provide a way to parameterize types, functions, and classes so that they can work with a variety of data types.

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

const numberValue: number = identity(5);
const stringValue: string = identity("Hello");
```
In this example, we define a generic function `identity<T>(arg: T): T`. The `T` within angle brackets represents a generic type. The function takes an argument of type `T` and returns the same type `T`. We can call this function with different types, such as `number` and `string`, and TypeScript infers the appropriate types for each call.

**Question:** The following TypeScript code is intended to merge two objects. However, it contains a syntax error and doesn’t compile. Identify the error and fix the code.

```javascript
function mergeObjects(obj1: object, obj2: object): object {
  return { ...obj1, ...obj2 };
}

const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const mergedObj = mergeObjects(obj1, obj2);
console.log(mergedObj);
```
**Answer:** The syntax error in the code is that the `object` type doesn’t allow for spread operators. To fix the code, we should use the `Record<string, any>` type to represent a dictionary-like object with any property names.

```javascript
function mergeObjects(obj1: Record<string, any>, obj2: Record<string, any>):
 Record<string, any> {
  return { ...obj1, ...obj2 };
}

const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const mergedObj = mergeObjects(obj1, obj2);
console.log(mergedObj);
```

In this corrected code, we use the `Record<string, any>` type to represent objects with string keys and any values, allowing us to use spread operators for merging.

**Question:** Explain the concept of decorators in TypeScript and provide an example of how they can be used.
**Answer:** Decorators in TypeScript are a way to modify classes, methods, or properties at design time. They allow us to enhance the behavior of these elements by attaching metadata or additional functionality.

Example:
```javascript
function logDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;

descriptor.value = function (...args: any[]) {
    console.log(`Calling method ${propertyKey} with arguments ${args}`);
    const result = originalMethod.apply(this, args);
    console.log(`Method ${propertyKey} returned: ${result}`);
    return result;
  };

return descriptor;
}

class Calculator {
  @logDecorator
  add(a: number, b: number) {
    return a + b;
  }
}

const calculator = new Calculator();
const sum = calculator.add(5, 3);
```
In this example, we define a decorator function `logDecorator`. When applied to the `add()` method of the `Calculator` class using the `@logDecorator` syntax, it modifies the behavior of the method. The decorator logs the method call with its arguments and the return value before and after the original method execution.

## Interview best practices for TypeScript roles

For successful TypeScript interviews, taking into account multiple aspects such as the applicant’s experience level and the engineering position is crucial. To guarantee that your TypeScript interview inquiries produce optimal outcomes, we suggest adhering to the following best practices when engaging with candidates:

- Devise technical queries that correspond with real-world business scenarios within your organization. This approach not only makes the interview more captivating for the applicant but also allows you to more effectively gauge their fit for your team.
- Encourage the candidate to pose questions throughout the interview and cultivate a cooperative atmosphere.
- Assess their knowledge of TypeScript best practices, including using strict mode, avoiding the ‘any’ type when possible, and leveraging the power of the type system to write clean, maintainable code.
