You are currently viewing Top 10 TypeScript Interview Questions and Answers
Are you preparing for a TypeScript interview? Look no further! In this article, we will cover the top 10 TypeScript interview questions and provide detailed answers to help you ace your interviews.

Top 10 TypeScript Interview Questions and Answers

1. What is TypeScript?

TypeScript is a strongly typed superset of JavaScript that compiles to plain JavaScript. It adds static types, classes, interfaces, and other features to JavaScript, making it more suitable for large-scale application development.

// Example
let greeting: string = 'Hello, TypeScript!';
console.log(greeting);

2. What are the advantages of using TypeScript?

  • Type Safety: TypeScript helps catch potential errors during development.
  • Enhanced Tooling: TypeScript provides autocompletion, refactoring, and navigation features in IDEs.
  • Improved Code Readability: TypeScript’s static typing makes code more self-documenting.
// Example
interface Person {
  name: string;
  age: number;
}

function greet(person: Person): string {
  return `Hello, ${person.name}! You are ${person.age} years old.`;
}

const user: Person = {
  name: 'John Doe',
  age: 30
};

console.log(greet(user));

3. Explain the difference between interfaces and classes in TypeScript.

Interfaces are used to define contract-like structures in TypeScript and cannot be implemented directly. On the other hand, classes can be instantiated and have both properties and methods. Classes can also implement interfaces.

// Example
interface Animal {
  name: string;
  sound: string;
}

class Dog implements Animal {
  name: string;
  sound: string;

  constructor(name: string) {
    this.name = name;
    this.sound = 'Woof!';
  }

  bark(): void {
    console.log(this.sound);
  }
}

const dog = new Dog('Buddy');
dog.bark(); // Output: Woof!

4. How do you handle asynchronous operations in TypeScript?

TypeScript provides several mechanisms for handling asynchronous operations, such as promises, async/await, and callbacks. Promises are the recommended approach for modern asynchronous programming in TypeScript.

// Example using promises
function fetchData(): Promise<string> {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Data fetched successfully!');
    }, 2000);
  });
}

fetchData()
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.log(error);
  });

5. How can you achieve code reusability in TypeScript?

In TypeScript, code reusability can be achieved through inheritance and composition. Inheritance allows a class to inherit properties and methods from another class. Composition involves creating a new class by combining existing classes to leverage their functionalities.

// Example using inheritance
class Vehicle {
  engine: string;

  constructor(engine: string) {
    this.engine = engine;
  }

  start(): void {
    console.log(`Starting ${this.engine}...`);
  }
}

class Car extends Vehicle {
  wheels: number;

  constructor(engine: string, wheels: number) {
    super(engine);
    this.wheels = wheels;
  }

  drive(): void {
    console.log(`Driving with ${this.wheels} wheels...`);
  }
}

const car = new Car('V6', 4);
car.start(); // Output: Starting V6...
car.drive(); // Output: Driving with 4 wheels...

6. How can you handle null and undefined values in TypeScript?

TypeScript introduces the concepts of nullable and undefined types. To handle null and undefined values, you can use type unions or the strictNullChecks compiler flag.

// Example
let value: string | null;
value = 'Hello';
value = null;
console.log(value);

7. What are modules in TypeScript?

Modules in TypeScript are used to organize code into reusable components. They help in creating a clear separation of concerns and provide better code organization and maintainability.

// Example
// file: math.ts
export function add(a: number, b: number): number {
  return a + b;
}

// file: main.ts
import { add } from './math';

console.log(add(5, 3)); // Output: 8

8. How can you extend the functionality of existing types in TypeScript?

TypeScript allows you to extend the functionality of existing types using declaration merging. This feature enables you to add properties or methods to interfaces, classes, or other types defined in external libraries.

// Example
interface Person {
  name: string;
}

interface Person {
  age: number;
}

const person: Person = {
  name: 'John Doe',
  age: 30
};

console.log(person.name); // Output: John Doe
console.log(person.age); // Output: 30

9. How can you create and use generic types in TypeScript?

Generic types in TypeScript allow you to create reusable and flexible components. They enable you to define type parameters that can be used in multiple places within your code.

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

console.log(identity('Hello')); // Output: Hello
console.log(identity(123)); // Output: 123

10. What are decorators in TypeScript?

Decorators are a TypeScript feature that allows for adding metadata or additional functionality to classes, methods, properties, or parameters at runtime. They are similar to annotations in other languages.

// Example
function log(target: any, name: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;

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

  return descriptor;
}

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

const calculator = new Calculator();
calculator.add(3, 5); // Output: Calling method add with arguments 3,5

These are just a few of the many TypeScript interview questions you may encounter. Remember to practice and understand the concepts thoroughly to excel in your TypeScript interviews.