Best 7 TypeScript Interview Questions

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:

  1. Static Typing: TypeScript is a typed language that allows you to catch errors at compile time. This means you can identify issues before running your code, which saves time and effort during debugging.
  2. Object-Oriented Features: TypeScript supports classes and interfaces, making it easier to write well-organized and maintainable code. You can define custom types and structures, enhancing the clarity of your codebase.
  3. Tooling and IntelliSense: TypeScript provides excellent tooling support. Features like IntelliSense offer dynamic hints as you write code, improving productivity and reducing errors.
  4. Code Organization: TypeScript helps maintain a structured codebase. It encourages better practices by enforcing type checks and providing a more robust development experience.
  5. Compatibility with JavaScript: TypeScript can be transpiled into plain JavaScript, allowing you to leverage existing JavaScript libraries and frameworks seamlessly.
  6. Better Documentation: TypeScript offers well-documented APIs that align with the source code. This clarity aids developers in understanding and using the available functionality.
  7. Reduced Bugs: Many companies report a reduction in bugs after transitioning to TypeScript.

However, it’s essential to consider the disadvantages as well:

  1. Compilation Time: TypeScript takes longer to compile compared to JavaScript due to its type checking.
  2. Third-Party Libraries: When using external libraries, you might need definition files (.d.ts) to provide type information. Sometimes these files are not readily available or may have quality issues.
  3. Learning Curve: Developers familiar with JavaScript may take some time to adapt to TypeScript. It typically takes around 2-3 months for teams to become productive and about 6 months to become proficient.In summary, TypeScript’s static typing, object-oriented features, and improved tooling make it a compelling choice for large projects, while JavaScript remains suitable for simpler web applications and smaller projects.


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:

  1. Optional Chaining (?.):Purpose: Optional chaining allows you to safely access properties or methods of an object without causing runtime errors if the property or method is null or undefined.How it works:If the property or method exists, it is accessed normally.If the property or method is null or undefined, the expression evaluates to undefined.

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

  1. Nullish Coalescing (??):Purpose: Nullish coalescing provides a way to provide a default value when dealing with null or undefined values.How it works:If the left-hand side expression is null or undefined, it evaluates to the right-hand side value.Otherwise, it evaluates to the left-hand side value.

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:

  1. Asynchronous Operations in TypeScript:Asynchronous operations involve tasks that don’t block the execution of other code. Common examples include making network requests, reading files, or querying databases.In TypeScript, you can handle asynchronous operations using:Callbacks: Functions that are called when an operation completes.Promises: Objects representing the eventual completion (or failure) of an asynchronous operation.Async/await: A more readable and concise way to work with Promises.
  2. Advantages of async/await over Callbacks and Promises:Readability: async/await makes code more synchronous-like and easier to read. It avoids the callback hell (nested callbacks) that can occur with traditional callback-based code.Error Handling: With try/catch blocks, async/await provides better error handling. Errors can be caught at the point where they occur, improving code robustness.Sequential Execution: await ensures that asynchronous operations execute sequentially, making it simpler to reason about the flow of your code.Clean Syntax: The syntax of async/await is cleaner and more intuitive than chaining .then() methods with Promises.Type Safety: TypeScript’s type system works seamlessly with async/await, allowing you to catch type-related errors early during development.

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:

  1. Defining Enums:You can define an enum using the enum keyword.TypeScript supports both numeric and string-based enums.
  2. Numeric Enums:Numeric enums are familiar if you’ve worked with enums in other languages.

Example: enum Direction {

????Up = 1,

????Down,

????Left,

????Right,

}

  • Here, Up is initialized with 1, and subsequent members auto-increment from that point.

Accessing enum members: const userResponse = Direction.Down;

  1. String Enums:String enums use string literals as values.

Example: enum Color {

????Red = "RED",

????Green = "GREEN",

????Blue = "BLUE",

}

  • String enums don’t auto-increment but provide meaningful values.Useful for serialization and readability.

  1. Advantages of Enums:Readability: Enums give names to otherwise arbitrary numeric or string values, making code more self-explanatory.Type Safety: Enums provide type safety, catching mistakes during development.Maintainability: Centralize updates by defining constants in one place.Serialization: String enums serialize well, conveying meaningful values at runtime.

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:

  1. What are Type Guards?:A type guard is a piece of code that checks the type of a variable and narrows down its type within a specific scope.When a type guard passes, TypeScript infers a more specific type for the variable.
  2. Common Type Guards:TypeScript provides several built-in type guards:typeof: Checks the type using the typeof operator.instanceof: Determines if an object is an instance of a given constructor function or class.in: Checks if an object contains a specific property.Equality narrowing type guard: Compares values using equality operators.Custom type guard with predicate: User-defined functions that return a boolean based on custom conditions.

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.

  1. In the example above:The isString function acts as a custom type guard.If value is a string, TypeScript narrows its type within the if block.Otherwise, it falls into the else block.Custom type guards allow you to express your assumptions about types more explicitly, leading to safer and more reliable code in TypeScript.

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

  1. In this example, the name property is marked as readonly. You can only assign its value during object creation or in the constructor.

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

  1. The name property in the Product class is also marked as readonly. It can be set only during object construction.

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

  1. The x and y properties in the Point type are both read-only. Once initialized, their values cannot change.

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:

  1. Basic Union Type 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

  • In this example, the id parameter can be either a string or a number. The vertical bar (|) separates the possible types.

  1. Other Use Cases:Union types are helpful when dealing with APIs that return data in multiple formats or when working with data that can take on different forms.You can use union types for properties that could be either a string or an array, or for handling different status codes (e.g., 200 or 404).
  2. Custom Union Types:

You can create your own union types by combining existing types: type Status = "success" | "error" | "pending";

const currentStatus: Status = "success"; // Valid

  • Here, Status can only be one of the specified literal values: "success", "error", or "pending".

In summary, union types allow you to express flexibility in the types a variable can hold, making your code more versatile and expressive.

要查看或添加评论,请登录

MD RAHATUL ISLAM的更多文章

社区洞察

其他会员也浏览了