Best 7 TypeScript Interview Questions
Q-1.?What are some benefits of using TypeScript over JavaScript in a project?
Answer: There are many advantages and disadvantages of using TypeScript over JavaScript. Here are some advantages of using TypeScript over JavaScript in a project:
However, it’s essential to consider the disadvantages as well:
Q-2.?What is the purpose of the optional chaining (?.) and nullish coalescing (??) operators in TypeScript, and how do they work? Provide an example for each.
Let’s delve into the optional chaining and nullish coalescing operators in TypeScript, along with examples for each:
Example: interface Person {
????name: string;
????address?: {
????????street?: string;
????????city?: string;
????};
}
const person: Person = {
????name: "Alice",
????// address is not defined
};
const city = person.address?.city; // Safely accesses city property
console.log(city); // Output: undefined
Example: const username: string | undefined = getUserFromAPI(); // Assume this function returns undefined
const defaultUsername = "Guest";
const finalUsername = username ?? defaultUsername;
console.log(finalUsername); // Output: "Guest"
In summary, optional chaining helps prevent runtime errors when accessing properties, and nullish coalescing provides a fallback value when dealing with nullish values. These operators enhance code safety and readability in TypeScript.
Q-3.?How do you handle asynchronous operations in TypeScript, and what are the advantages of using async/await over callbacks or Promises?.
Let’s explore how asynchronous operations are handled in TypeScript and the advantages of using async/await over callbacks or Promises:
Example: // Using Promises
function fetchData(): Promise<string> {
????return fetch("https://api.example.com/data")
????????.then((response) => response.json())
????????.then((data) => data.message);
}
// Using async/await
async function fetchDataAsync(): Promise<string> {
????try {
????????const response = await fetch("https://api.example.com/data");
????????const data = await response.json();
????????return data.message;
????} catch (error) {
????????console.error("Error fetching data:", error);
????????throw error;
????}
}
// Usage
fetchDataAsync()
????.then((result) => console.log("Data:", result))
????.catch((error) => console.error("Error:", error));
In summary, async/await simplifies asynchronous code, enhances readability, and provides better error handling. It’s a powerful tool for managing asynchronous operations in TypeScript.
Q-4.?How can you use TypeScript's enums, and what are their advantages?.
Enums in TypeScript allow you to define a set of named constants. They provide several advantages, making your code more readable, maintainable, and expressive. Let’s explore how to use enums and their benefits:
Example: enum Direction {
????Up = 1,
????Down,
????Left,
????Right,
}
Accessing enum members: const userResponse = Direction.Down;
Example: enum Color {
????Red = "RED",
????Green = "GREEN",
????Blue = "BLUE",
领英推荐
}
In summary, enums organize your code, improve readability, and enhance maintainability. They’re a powerful tool in TypeScript development.
Q-5.?Explain the role of type guards in TypeScript and provide an example of a custom type guard.
Type guards in TypeScript play a crucial role in narrowing down the type of a variable within specific blocks of code. They allow you to perform runtime checks and provide more precise type information. Let’s explore type guards and create a custom example:
Custom Type Guard Example: // Custom type guard for checking if a value is a string
function isString(value: unknown): value is string {
????return typeof value === "string";
}
// Usage
function processValue(value: unknown) {
????if (isString(value)) {
????????// Inside this block, TypeScript knows that 'value' is a string
????????console.log("Length of the string:", value.length);
????} else {
????????console.log("Not a string.");
????}
}
// Example usage
processValue("Hello, TypeScript!"); // Output: Length of the string: 18
processValue(42); // Output: Not a string.
Q-6.?What is readonly property in TypeScript? Can you give an example of how to use "readonly" properties in TypeScript?
Certainly! In TypeScript, the readonly modifier is used to create properties that cannot be modified after their initial assignment. These properties are immutable once set. Here’s how you can use readonly properties:
Interface with Readonly Property: interface IPerson {
????readonly name: string;
????role: string;
}
const person: IPerson = {
????name: 'Tim', // Readonly property
????role: 'admin'
};
// Attempting to modify the name property will result in an error:
// person.name = 'Alice'; // Error: Cannot assign to 'name' because it is a read-only property
Class with Readonly Property: class Product {
????readonly name: string;
????price: number;
????constructor(name: string, price: number) {
????????// ? Only assign in the constructor or property declaration
????????this.name = name;
????????this.price = price;
????}
}
const laptop = new Product('Laptop', 1000);
// laptop.name = 'Desktop'; // Error: Cannot assign to 'name' because it is a read-only property
Type with Readonly Properties: type Point = {
????readonly x: number;
????readonly y: number;
};
const origin: Point = { x: 0, y: 0 };
// origin.x = 10; // Error: Cannot assign to 'x' because it is a read-only property
In summary, readonly properties ensure immutability and help maintain data integrity in your TypeScript code. They are particularly useful for representing constant values or properties that should not be modified after initialization . ??
Q-7.?Explain what a union type is in TypeScript and provide an example of its usage.
In TypeScript, a union type allows you to express a value that can be one of several different types. It’s particularly useful when a variable or parameter can hold values of multiple types. Let’s dive into union types and see an example:
Suppose we have a function that accepts an argument that can be either a string or a number: function printId(id: string | number) {
????console.log(`ID is: ${id}`);
}
printId("abc"); // Outputs: ID is: abc
printId(123); ? // Outputs: ID is: 123
You can create your own union types by combining existing types: type Status = "success" | "error" | "pending";
const currentStatus: Status = "success"; // Valid
In summary, union types allow you to express flexibility in the types a variable can hold, making your code more versatile and expressive.