TypeScript Interview Questions

TypeScript Interview Questions and Answers (2026)

March 20th, 2026
1467
15:00 Minutes

Over the years TypeScript has transitioned from a specialized form of JavaScript into one of the primary languages that is used today to develop web applications. During my professional time developing web apps, I have noticed that the use of strong typing and maintainability can greatly reduce the number of bugs in your code as well as increase the overall quality of communication between multiple teams working on the same project.

As I have worked through job postings for developer positions, TypeScript is being listed as a primary requirement, rather than an optional series of skills.

In this blog, I will provide you with some of the most commonly asked TypeScript interview questions that are suitable for all levels, whether you are a fresher or an experienced professional. I have also given some code examples as it becomes easier for them to connect theory with real usage. Let’s begin!

TypeScript Interview Questions for Freshers

Following are some TypeScript Interview Questions for Freshers that are asked to candidates to check how strong their basic knowledge is:

1. What is TypeScript and how is it different from JavaScript?

TypeScript is a superset of JavaScript created by Microsoft. It adds static typing, interfaces and better tooling to JavaScript. TypeScript code is compiled into normal JavaScript before running in a browser or Node.js. This helps catch errors during development and improves code readability and maintainability.

For example:

let name: string = "Nehal";

2. What are the basic data types in TypeScript?

TypeScript includes several basic data types such as string, number, boolean, null, undefined, any, void, arrays and tuples. These types define the kind of data a variable can store. Using these types improves code readability and helps prevent errors during development.

For example:

let age: number = 20;
let isStudent: boolean = true;
let name: string = "Nehal";

3. What is type inference?

Type inference means TypeScript automatically determines the type of a variable based on the value assigned to it. Developers do not always need to specify the type manually. This feature makes coding faster while still maintaining type safety and reducing mistakes.

4. What are type annotations?

Type annotations are used to explicitly define the type of a variable, function parameter or return value. They help developers clearly specify what type of data should be used which makes the code easier to understand and reduces the chances of errors.

5. What is any type and when should it be avoided?

Any type allows a variable to hold any kind of value, which disables TypeScript’s type checking. It should be avoided because it removes type safety and may lead to unexpected errors in the program. It should only be used when the type of data is unknown.

6. What is an interface in TypeScript?

An interface in TypeScript is used to define the structure or shape of an object. It specifies the properties and their types that an object should have. Interfaces help ensure consistency in objects and make code more organized and easier to maintain.

7. What is the difference between interface and a type?

In TypeScript, both interfaces and types are used to describe how data should look, but they differ in how flexible they are and how they are used.

Parameters Interface Type
Purpose Used mainly to define the structure of objects. Can define objects, primitives, unions, tuples and more.
Flexibility Less flexible as it is mostly used for object shapes. More flexible because it can represent many kinds of types.
Declaration Merging Supports declaration merging (multiple interfaces with same name combine). Does not support declaration merging
Extending Can extend other interfaces using extends. Can extend using intersection (&) types.
Common Usage Mostly used for OOP and APIs. Used when you need complex or advanced type combinations.

8. What are union types?

Union types allow a variable to store more than one possible type of value. Rather than restricting a variable to a single type, union types provide flexibility while still maintaining type checking in TypeScript.

9. What are tuples in TypeScript?

A tuple is a special type of array where the number of elements and their data types are fixed. Each position in the tuple has a specific type. Tuples are useful when storing multiple related values with different data types.

10. What are optional properties in interfaces?

Optional properties are properties in an interface that are not required when creating an object. They are marked using a question mark. This allows objects to be created even if some properties are missing, making interfaces more flexible.

Read Also: Java Tutorial for Beginners

Intermediate TypeScript Interview Questions

Following are some TypeScript questions for intermediate level candidates and these questions are asked to test what you learned in your previous job role:

1. What are generics in TypeScript?

Generics allow developers to create reusable components that can work with different data types while maintaining type safety. Instead of using a fixed type, a type parameter is passed when the function, class or interface is used.

For example:

function identity(value: T): T {
  return value;
}

let num = identity(10);
let str = identity("Hello");

console.log(num);
console.log(str);

generics in typescript

Code Explanation:

  • <T> is a generic type parameter that represents any type.
  • value: T means the function accepts a value of type T.
  • : T after the function means the return type will also be T.
  • identity(10) tells TypeScript that T is number.
  • identity("Hello") tells TypeScript that T is string.
  • This makes the function reusable for different types while keeping type safety.

2. What are type guards?

Type guards are techniques used to narrow down the type of a variable within a conditional block. They help TypeScript identify the correct type during runtime checks using conditions such as typeof, instanceof or custom checking functions.

3. What is the keyof keyword?

keyof is a TypeScript operator that creates a union type of all property names of a given object type. It is commonly used with generics to safely access object properties.

For example:

function printValue(value: string | number) {
  if (typeof value === "string") {
    console.log(value.toUpperCase());
  } else {
    console.log(value.toFixed(2));
  }
}

// Function calls
printValue("hello");
printValue(12.345);

keyof keyword in typescript

Code Explanation:

  • printValue is a function that accepts a parameter value which can be either a string or a number (union type).
  • typeof value === "string" checks the runtime type of value and acts as a type guard.
  • If value is a string, toUpperCase() converts the text to uppercase letters.
  • If value is a number, toFixed(2) formats the number to two decimal places.
  • The function is called twice: once with a string ("hello") and once with a number (12.345), producing different outputs based on the type.

4. What are utility types in TypeScript?

Utility types are built-in generic types that help transform existing types. They allow developers to easily modify properties, such as making them optional, required or read only, without rewriting the entire type.

5. What is the Partial <T> utility type?

Partial <T> is a utility type that makes all properties of a given type optional. It is useful when working with objects where only some properties need to be updated or provided.

For example:

type User = {
  name: string;
  age: number;
};

function updateUser(user: User, updates: Partial) {
  return { ...user, ...updates };
}

const user = { name: "Alice", age: 25 };

const updatedUser = updateUser(user, { age: 26 });

console.log(updatedUser);

partial t utility type in typescript

Code explanation:

  • User is a type that defines an object with name and age.
  • updateUser is a function that accepts a User object and updates using Partial.
  • Partial makes all properties optional (name?, age?).
  • The spread operator { ...user, ...updates } merges the old user with new updates.
  • console.log(updatedUser) prints the updated object to the console.

6. What is the difference between unknown and any?

Any allows a variable to hold any type and disables type checking. Unknown is safer because TypeScript requires the type to be checked before performing operations on the variable.

Here is a brief differentiation of them:

Parameters any unknown
Type Safety Disables TypeScript type checking. You can perform any operation without errors. Type safe TypeScript requires you to check the type before using it.
Purpose Used when you don't want type checking. Used when you don’t know the type yet but want safety.
Usage Can be used directly without validation. Must be type-checked or type-casted before using.
Risk Level Risky because it may cause runtime errors. Safer because TypeScript forces validation.
Assignment Can be assigned to any other type without restriction. Can only be assigned to unknown or any unless you narrow the type.

For example:

let value: unknown = "Hello";

if (typeof value === "string") {
  console.log(value.toUpperCase());
}

let anything: any = "Hello";
console.log(anything.toUpperCase());

difference between unknown and any in typescript

Code explanation:

  • unknown can store any value but requires type checking before use.
  • typeof value === "string" ensures the value is a string.
  • Only after this check can we call toUpperCase().
  • any disables type checking completely.
  • With any, TypeScript allows any operation, which can lead to runtime errors.

7. What are mapped types?

Mapped types allow developers to create new types by transforming the properties of an existing type. They iterate over each property in a type and apply changes such as making them readonly or optional.

8. What is typeof in TypeScript?

typeof is used to get the type of a variable or object and reuse that type elsewhere in the code. It helps maintain consistency between values and their types.

9. What are namespaces and modules?

Namespaces are used to organize code into logical groups within the same file. Modules organize code across multiple files using import and export, making the code more modular and maintainable.

Namespace Example:

namespace MathUtils {
  export function add(a: number, b: number) {
    return a + b;
  }
}

console.log(MathUtils.add(2, 3));

namespaces and modules in typescript

Code explanation:

  • namespace MathUtils groups related functions together in TypeScript.
  • export function add(a: number, b: number) defines a function that takes two numbers.
  • The function returns the sum using return a + b.
  • MathUtils.add(2,3) calls the function and computes 5.
  • console.log() prints the returned value to the output console.

10. What are decorators in TypeScript?

Decorators are special functions used to add metadata or modify the behavior of classes, methods, properties or parameters. They are commonly used in frameworks like Angular for adding functionality.

Read Also: Java Interview Questions and Answers

TypeScript Interview Questions for Experienced Professionals

Following are the interview questions for TypeScript that are asked to those candidates who have 4+ years of work experience, to make sure that they can handle complex tasks easily:

1. Can you explain conditional types in TypeScript?

Conditional types allow you to define types based on a condition, similar to ternary operators in JavaScript. They are used in dynamic type transformation based on input type.

They follow a certain pattern and that is:

T extends U ? X : Y

2. What is the infer keyword?

infer is used within conditional types to extract and infer a type from another type. It provides capturing parts of complex types, such as return types or array elements, dynamically.

For example:

type Node = {
  value: string;
  children?: Node[];
};

const tree: Node = {
  value: "root",
  children: [
    { value: "child1" },
    { value: "child2", children: [{ value: "grandchild" }] }
  ]
};

console.log(tree);

infer keyword in typescript

Code explanation:

  • type Node defines the structure of a tree node with a value (string) and optional children.
  • children?: Node[] means each node can contain an array of same type nodes, forming a tree.
  • The ? makes children optional, so leaf nodes don’t need to have children.
  • const tree: Node = {...} creates an actual tree object following the defined type.
  • Inside children, you can nest more nodes, allowing multi-level (parent → child → grandchild).
  • TypeScript ensures that every node must follow the Node structure, preventing invalid data.
  • console.log(tree) prints the tree, since types alone don’t produce output in JavaScript.

3. What are recursive types?

Recursive types are types that refer to themselves. They are useful for defining data structures that are nested, like trees or JSON objects.

For example:

type Node = {
  value: string;
  children?: Node[];
};

const tree: Node = {
  value: "root",
  children: [{ value: "child" }]
};

console.log(tree.children?.[0].value); // child

recursive types in typescript

Code Explanation:

  • The Node type defines a structure where each item has a value and can optionally have children, which is an array of similar Node objects.
  • This makes it a recursive type, meaning a node can contain more nodes inside it like a tree or hierarchy.
  • The tree object follows this structure: it has a root node with value "root" and one child node with value "child".
  • The children property is optional (?). A node may or may not have children.

4. What are template literal types in TypeScript?

Template literal types let you create string types using a pattern, just like JavaScript template strings. You can combine strings and even modify them using built in helpers like Capitalize. This is useful for creating consistent naming patterns like event names or API routes and helps avoid mistakes in string values.

For example:

type EventName = `on${Capitalize}`;

function trigger(event: EventName<"click">) {
  console.log(event);
}

trigger("onClick"); // onClick

template literal types in typescript

Code explanation:

  • Builds string using template.
  • Capitalize modifies text.
  • Ensures strict naming pattern.
  • Prevents wrong string usage.
  • Output matches formatted string.

5. What is module augmentation?

Module augmentation is a way to extend existing modules or libraries without changing their original code. You can add new properties or methods to already defined types. This is especially useful when working with third party libraries where you want to customize or enhance their type definitions safely.

6. What are discriminated unions in TypeScript?

Discriminated unions are a way to handle multiple related types safely. Each type has a common property, like type or kind, which helps TypeScript identify which type is being used. Based on that value, TypeScript can automatically understand the correct structure and give better type checking.

For example:

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number };

function area(shape: Shape) {
  if (shape.kind === "circle") return 3.14 * shape.radius ** 2;
  return shape.side ** 2;
}

console.log(area({ kind: "circle", radius: 2 })); // 12.56

discriminated unions in typescript

Code explanation:

  • Uses common kind property.
  • Helps identify type safely.
  • TypeScript narrows type.
  • No need for manual casting.
  • Output depends on shape type.

7. What is type erasure?

Type erasure means that TypeScript removes all type information when converting code to JavaScript. Types are only used during development for checking errors. After compilation, only plain JavaScript remains. This ensures there is no extra runtime cost while still getting the benefits of type safety during coding.

8. How does TypeScript handle large-scale application architecture?

TypeScript helps manage large applications by providing strong typing, modules and reusable components. It makes code more organized and easier to maintain. Features like interfaces, generics and strict settings help catch errors early. It also supports splitting projects into smaller parts which makes the development faster and more scalable.

For example:

function add(a: number, b: number): number {
  return a + b;
}

// calling the function
const result = add(5, 5);

// output
console.log("Result is:", result);

large scale application architecture in typescript

Code explanation:

  • add(a: number, b: number): function takes two numbers as input
  • : number: ensures function returns a number (TypeScript safety)
  • return a + b: adds both values
  • const result = add(5, 5): function is called and stored
  • console.log(...): prints output to screen

9. How do you create reusable generic utility types?

You can create reusable utility types using generics, which work with different types instead of one fixed type. This helps avoid repeating code. By combining generics with mapped and conditional types, you can build flexible tools like making properties optional or read only.

10. How do you ensure type safety in complex TypeScript projects?

To ensure type safety, you should use strict TypeScript settings and avoid using any. Define clear interfaces and use generics where needed. Type guards and unions help handle different cases safely. Follow good coding practices, use linters and write tests. This reduces bugs and keeps the code reliable and easy to maintain.

For example:

type User = { name: string };

function print(user: User) {
  console.log(user.name);
}

print({ name: "Nehal" }); // Nehal
// print({ age: 20 });  Error

type safety in complex typescript projects

Code explanation:

  • Defines strict structure.
  • Prevents invalid data.
  • Errors caught at compile time.
  • Avoids runtime bugs.
  • Output works only for valid input.

Scenario-Based TypeScript Interview Questions

Your interviewer will ask you these questions just to test how you think and apply concepts in real situations, not just whether you remember syntax. Here are some of them:

1. While developing a backend API using NestJS, you want to automatically log every time a service method is executed instead of writing logging code inside each function. How would you design and implement a reusable TypeScript decorator that logs method calls across multiple services?

I would create a custom method decorator in TypeScript that wraps the original function. Inside the decorator, I would capture the method name, arguments and execution time. Before the method runs, I would log that the method is being called and after execution, I would log the result or completion message.

This way, I don’t need to add logging manually in every service method. I can simply apply the decorator wherever needed. This approach keeps my code clean, avoids repetition and makes logging reusable across different services in my NestJS application.

2. Your team is creating a configuration object for an application and you want to ensure the object follows a required interface while still preserving literal types for stricter type checking. How would you use the satisfies operator in TypeScript to validate the configuration object without widening its types?

I would use the satisfies operator when defining my configuration object. This helps me ensure that the object matches the required interface, so all necessary properties are present and correctly typed.

This means I get strict type checking and better auto completion in my code. It also helps catch errors early if I use incorrect values. Overall, it gives me both validation and precision without losing the benefits of literal types.

3. You are developing a utility function that accepts an array of string literals and should return them while preserving the exact literal types instead of converting them to general string[]. How would you use const type parameters in TypeScript to maintain literal type inference?

I would use const type parameters to tell TypeScript to keep the exact values of the array instead of converting them into a general type. When I give TypeScript an array of specific text values, it remembers each exact value instead of seeing them all as just general “strings.” This helps maintain strong type safety and allows me to use those exact values later in my code.

It is especially useful when I want precise control over allowed values. This approach improves accuracy, prevents unexpected errors and makes my utility function more reliable and predictable.

4. In a Node.js application, developers often forget to close file handles or database connections, leading to memory leaks. How could you use the using declaration in TypeScript to ensure automatic resource cleanup when working with files or database connections?

I would use the using declaration to manage resources like file handles or database connections. TypeScript always makes sure that once the resource goes out of scope, it is automatically cleaned up. This means I don’t have to manually close connections every time.

Even if an error happens, the cleanup will still run properly. This reduces the risk of memory leaks and improves application stability. It also makes my code cleaner and easier to maintain because I don’t need to write extra cleanup logic everywhere.

5. You are designing a function that accepts a variable number of parameters, but the function must always append a numeric value at the end of the tuple. How would you use variadic tuple types in TypeScript to implement this behavior?

I would use variadic tuple types to allow my function to accept any number of parameters while enforcing that the last value must always be a number. This means I can take flexible input, like multiple values of different types, but TypeScript will still ensure that a numeric value is always present at the end.

This gives me both flexibility and type safety. It helps prevent mistakes where the required number might be missing. Using this approach makes my function more structured while still being flexible for different use cases.

6. You are building a utility library where the return type of a function should change depending on the input type. How would you implement this behavior using conditional types in TypeScript?

I would use conditional types to check the input type and decide the return type based on that condition. For example, if the input type is a string, the return type would be true; otherwise, it would be false. This allows my function to behave differently depending on the type of data it receives.

It improves type safety and makes my function smarter because TypeScript can predict the output type. This is very useful when building reusable libraries where behavior depends on input types. It helps catch errors early and improves developer experience.

7. While preparing a user object to send to the frontend, you want to ensure that all properties become read-only to prevent accidental modification. How would you use mapped types in TypeScript to convert every property of an object type into a read-only property?

I would use mapped types to loop through all properties of the object and mark each one as read-only. This means once the object is created, no one can modify its values. It is especially useful when sending data to the frontend, where I want to protect the original data from accidental changes.

This approach ensures data integrity and makes my application more predictable. It also helps other developers understand that the object should not be modified. Overall, it improves code safety and enforces better practices.

8. Your company is building a full-stack application using React on the frontend and Node.js on the backend and you want to ensure end-to-end type safety for API communication. How would tools like tRPC, Zod or GraphQL Codegen help achieve type-safe APIs across the entire application?

I would use tools like tRPC, Zod or GraphQL Codegen to ensure that the same types are shared between frontend and backend. These tools help define API contracts in one place and automatically use them everywhere. This means if I change something in the backend, the frontend will immediately reflect that change.

It reduces bugs caused by mismatched data and improves developer productivity. Zod helps with runtime validation, while tRPC and GraphQL Codegen ensure strong type safety. Overall, these tools make my application more reliable and easier to maintain.

9. Your development team notices that the TypeScript build process is slow in a large project with thousands of files. How would switching to tools like SWC, Rspack or Turbopack improve the build performance compared to traditional Babel-based setups?

I would switch to tools like SWC, Rspack or Turbopack because they are designed for high performance. These tools are written in faster languages like Rust, which makes them much quicker than Babel. They can process large codebases efficiently and reduce build times significantly.

This improves the developer experience because I don’t have to wait long for builds or reloads. It also helps in faster testing and deployment. Overall, these modern tools make development smoother and more efficient compared to traditional setups.

10. You are building a global application where APIs need to respond quickly to users across different regions, so you decide to deploy server logic closer to the users. How would platforms like Cloudflare Workers or Vercel Edge help implement edge computing with TypeScript and what advantages would this provide?

I would use platforms like Cloudflare Workers or Vercel Edge to run my server logic closer to users in different regions. This reduces the distance between the user and the server, which makes responses much faster. Using TypeScript ensures type safety while building these edge functions.

It also improves scalability because requests are handled at multiple locations instead of a single server. This approach reduces latency, improves performance and gives a better user experience globally. It is especially useful for applications with users from different parts of the world.

Wrapping Up

This article has covered a list of TypeScript interview questions with detailed answers. When you start exploring them, you get ready to tackle your next interview with full confidence. Keep practicing and exploring new trending technologies to stay updated with the real time knowledge.

FAQs

1. Why do interviewers ask TypeScript interview questions?

To understand problem solving skills and how features like types, interfaces and generics are used to write clean and maintainable code.

2. What kind of TypeScript questions are commonly asked in interviews?

Mostly scenario based questions about type safety, API handling, error management and application structure to test practical knowledge.

3. How should TypeScript interview questions be prepared?

You should start by understanding main concepts, practicing real examples and explaining ideas clearly instead of memorizing definitions.

Explore Our Trending Articles-

About the Author
Sanjay Prajapat
About the Author

Sanjay Prajapat is a Data Engineer and technology writer with expertise in Python, SQL, data visualization, and machine learning. He simplifies complex concepts into engaging content, helping beginners and professionals learn effectively while exploring emerging fields like AI, ML, and cybersecurity in today’s evolving tech landscape.

Drop Us a Query
Fields marked * are mandatory
×

Your Shopping Cart


Your shopping cart is empty.