savanka

100 TypeScript Interview Questions (2026)

Introduction

TypeScript has become one of the most sought-after programming languages for frontend and full-stack development. Companies like Microsoft, Google, Amazon, Meta, and many startups expect developers to have a solid understanding of TypeScript, especially when working with Angular, React, Node.js, or NestJS.

If you’re preparing for your next software engineering interview, this guide will help you master the most frequently asked TypeScript interview questions—from beginner concepts to advanced topics.

Each question includes a detailed explanation, practical examples, and interview tips to help you understand the concept instead of simply memorizing answers.

Beginner TypeScript Interview Questions

1. What is TypeScript?

Answer

TypeScript is an open-source programming language developed by Microsoft that extends JavaScript by adding static typing and other advanced features. Since TypeScript is a superset of JavaScript, every valid JavaScript program is also valid TypeScript.

TypeScript code is compiled (or transpiled) into plain JavaScript, which can then run in any modern browser or JavaScript runtime like Node.js.

Example

let name: string = "Sagar";
let age: number = 26;
let isDeveloper: boolean = true;

Why Companies Use TypeScript

  • Detects errors during development
  • Better IntelliSense support
  • Easier refactoring
  • Cleaner code
  • More maintainable applications

Interview Tip

A common interview question is:

“Does the browser understand TypeScript?”

The answer is No. Browsers only understand JavaScript. TypeScript must first be compiled into JavaScript.


2. Why should you use TypeScript instead of JavaScript?

Answer

Although JavaScript is powerful, it lacks static type checking. This often leads to runtime errors that can be difficult to detect during development.

TypeScript helps developers catch these issues before the application runs.

Advantages

  • Static typing
  • Better IDE support
  • Easier debugging
  • Excellent auto-completion
  • Improved maintainability
  • Safer refactoring
  • Better collaboration in large teams

Example

JavaScript

let age = "25";
age = true;

No error occurs.

TypeScript

let age: number = 25;
age = true;

Compiler Error

Type 'boolean' is not assignable to type 'number'

Interview Tip

Mention that TypeScript improves developer experience but does not improve browser performance, since it compiles to JavaScript.


3. What is the difference between TypeScript and JavaScript?

JavaScriptTypeScript
Dynamically typedStatically typed
No compilationCompiled to JavaScript
Limited IDE supportExcellent IDE support
Runtime error detectionCompile-time error detection
Easier for small appsBetter for large applications

Example

JavaScript

let user = "John";
user = 123;

Allowed.

TypeScript

let user: string = "John";
user = 123;

Compilation Error.

Interview Tip

Don’t simply say

TypeScript is JavaScript with types.

Instead explain that it provides additional features such as

  • Interfaces
  • Generics
  • Enums
  • Utility Types
  • Decorators
  • Type Inference

4. What are the primitive data types in TypeScript?

TypeScript supports the following primitive types:

  • string
  • number
  • boolean
  • bigint
  • symbol
  • null
  • undefined

Example

let name: string = "Sagar";

let age: number = 26;

let isActive: boolean = true;

let salary: bigint = 5000000000n;

let uniqueId: symbol = Symbol();

let city: null = null;

let country: undefined = undefined;

Interview Tip

Many candidates forget bigint and symbol.


5. What is Static Typing?

Static typing means the variable type is checked during compilation rather than while the program is running.

Example

let marks: number = 90;

marks = "Ninety";

Compiler Error

Type 'string' is not assignable to type 'number'

Benefits

  • Prevents bugs
  • Better code quality
  • Easier maintenance
  • Better documentation

6. What is Type Inference?

TypeScript can automatically determine a variable’s type without explicitly declaring it.

Example

let username = "Sagar";

TypeScript automatically infers

string

Similarly

let price = 250;

becomes

number

Interview Tip

Type inference reduces unnecessary type annotations while maintaining type safety.


7. What is the any type?

The any type disables type checking for a variable.

Example

let value: any;

value = 100;

value = "Hello";

value = true;

value = [];

Everything is allowed.

Why avoid any?

  • Removes TypeScript’s safety
  • Makes debugging harder
  • Hides compiler errors

Best Practice

Use unknown whenever possible instead of any.


8. What is the unknown type?

unknown is a safer alternative to any.

You cannot use an unknown value until you’ve checked its type.

Example

let value: unknown = "Savanka";

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

Why use unknown?

  • Safer
  • Prevents accidental misuse
  • Encourages proper type checking

Interview Tip

A common interview question is:

Difference between any and unknown?

anyunknown
No type checkingType checking required
UnsafeSafe
Can perform operations directlyMust narrow type first

9. What is the never type?

The never type represents values that never occur.

Usually used for

  • Functions that always throw errors
  • Infinite loops

Example

function throwError(message: string): never {
    throw new Error(message);
}

Another example

while (true) {

}

Interview Tip

Many developers confuse never with void.


10. What is the void type?

void indicates that a function does not return any value.

Example

function greet(): void {
    console.log("Welcome");
}

Difference

voidnever
Returns nothingNever returns
Function completesFunction never completes

11. What are Interfaces?

Interfaces define the structure of an object.

Example

interface User{

id:number;

name:string;

email:string;

}

Using it

const user:User={

id:1,

name:"Sagar",

email:"admin@savanka.com"

}

Benefits

  • Better readability
  • Strong type checking
  • Reusable contracts

12. What is a Type Alias?

Type aliases create a new name for any type.

Example

type Employee={

id:number;

name:string;

}

Unlike interfaces, aliases can represent primitive types, unions, tuples, and more.


13. Interface vs Type Alias

InterfaceType
Can be extendedCan use intersections
Better for objectsBetter for unions
Supports declaration mergingDoesn’t support declaration merging

Interview Tip

Modern TypeScript uses both depending on the use case.


14. What are Union Types?

A union allows a variable to hold multiple possible types.

Example

let id:number|string;

id=100;

id="EMP101";

Why useful?

APIs often return different types.


15. What are Intersection Types?

Intersection combines multiple types.

Example

type Person={

name:string;

}

type Employee={

salary:number;

}

type Staff=Person & Employee;

Staff now contains both properties.


16. What are Literal Types?

Literal types allow only specific values.

Example

type Direction="left"|"right"|"up"|"down";

Only these four values are valid.

Useful for

  • Themes
  • Roles
  • Status
  • API responses

17. What are Tuples?

Tuples are arrays with fixed types and order.

Example

let employee:[number,string];

employee=[1,"Sagar"];

Unlike arrays, order matters.


18. What are Enums?

Enums define named constants.

Example

enum Role{

Admin,

User,

Guest

}

Usage

let role=Role.Admin;

Benefits

  • Better readability
  • Avoid magic strings
  • Easier maintenance

19. What are Optional Properties?

Optional properties are marked using ?

Example

interface User{

name:string;

phone?:string;

}

The phone property is optional.


20. What are Readonly Properties?

Readonly properties cannot be modified after initialization.

Example

interface User{

readonly id:number;

name:string;

}

Trying to change

user.id=10;

Results in

Cannot assign to 'id' because it is a read-only property.

Best Practice

Use readonly for IDs, configuration values, and immutable data.

21. What are Generics in TypeScript?

Answer

Generics allow you to create reusable components, functions, classes, and interfaces that work with different data types while maintaining type safety.

Instead of writing separate functions for strings, numbers, and objects, you can write one generic function.

Without Generics

function getNumber(value: number): number {
    return value;
}

function getString(value: string): string {
    return value;
}

Notice how the logic is duplicated.

With Generics

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

identity<number>(10);
identity<string>("Savanka");
identity<boolean>(true);

Why use Generics?

  • Reusable code
  • Strong type checking
  • Less duplication
  • Better IntelliSense

Interview Tip

A common question is:

Why not use any instead?

any removes type safety, while generics preserve the actual type.


22. What are Generic Constraints?

Answer

Sometimes you don’t want a generic to accept every possible type.

Constraints allow you to restrict acceptable types.

Example

interface Person {
    name: string;
}

function printName<T extends Person>(user: T) {
    console.log(user.name);
}

Valid

printName({
    name: "Sagar",
    age: 26
});

Invalid

printName(10);

Why use Constraints?

  • Prevent invalid types
  • Improve code safety
  • Better compiler errors

23. What is the keyof operator?

Answer

keyof returns a union of all property names of a type.

Example

interface Employee {
    id: number;
    name: string;
    salary: number;
}

type Keys = keyof Employee;

Result

"id" | "name" | "salary"

Practical Example

function getValue<T, K extends keyof T>(
    obj: T,
    key: K
) {
    return obj[key];
}

Usage

getValue(employee, "name");

Interview Tip

keyof is commonly used with Generics.


24. What is the typeof operator?

Answer

typeof creates a type from an existing variable.

Example

const user = {
    name: "Sagar",
    age: 26
};

type User = typeof user;

Instead of manually defining the type, TypeScript derives it automatically.

Useful when objects become large.


25. What are Utility Types?

Answer

Utility Types are built-in helpers that transform existing types.

Examples

  • Partial
  • Required
  • Readonly
  • Pick
  • Omit
  • Record
  • Exclude
  • Extract
  • NonNullable

These utilities reduce repetitive code and improve maintainability.


26. What is Partial<T>?

Answer

Makes every property optional.

Example

interface User {
    id: number;
    name: string;
    email: string;
}

type UpdateUser = Partial<User>;

Now all fields become optional.

Valid

const user: UpdateUser = {
    name: "Rahul"
};

Perfect for Update APIs.


27. What is Required<T>?

Answer

Makes every optional property mandatory.

Example

interface User {
    id?: number;
    name?: string;
}

type UserRequired = Required<User>;

Now every property is compulsory.


28. What is Readonly<T>?

Answer

Converts every property into read-only.

Example

interface Product {
    id: number;
    price: number;
}

const product: Readonly<Product> = {
    id: 1,
    price: 500
};

Trying to modify

product.price = 600;

Compiler Error


29. What is Pick<T>?

Answer

Creates a new type by selecting only specific properties.

Example

interface Employee {
    id: number;
    name: string;
    salary: number;
    department: string;
}

type BasicInfo = Pick<Employee,
"id" | "name">;

Result

{
    id:number;
    name:string;
}

Useful when sending limited data.


30. What is Omit<T>?

Answer

Removes specific properties.

Example

type PublicEmployee =
Omit<Employee,
"salary">;

Salary no longer exists.

Useful when hiding sensitive data.


31. What is Record<K,T>?

Answer

Creates an object with predefined keys and value types.

Example

type Students = Record<
string,
number
>;

Usage

const marks: Students = {
    Rahul: 90,
    Aman: 85
};

Useful for lookup tables.


32. What is Exclude<T,U>?

Answer

Removes types from a union.

Example

type Status =
"Pending" |
"Completed" |
"Cancelled";

type Result =
Exclude<
Status,
"Cancelled"
>;

Result

"Pending" | "Completed"

33. What is Extract<T,U>?

Answer

Keeps only matching types.

Example

type A =
string |
number |
boolean;

type B =
Extract<A,
string | number>;

Result

string | number

34. What is NonNullable<T>?

Answer

Removes null and undefined.

Example

type User =
string |
null |
undefined;

type ValidUser =
NonNullable<User>;

Result

string

Useful for APIs.


35. What are Type Guards?

Answer

Type Guards help TypeScript determine the exact type at runtime.

Example

function print(
value:
string | number
) {

if(typeof value === "string"){

console.log(
value.toUpperCase()
);

}else{

console.log(
value.toFixed(2)
);

}

}

Without type guards, TypeScript cannot determine which methods are safe.


36. What is instanceof?

Answer

Checks whether an object belongs to a specific class.

Example

class Dog{

bark(){}

}

class Cat{

meow(){}

}

function speak(
animal:
Dog|Cat
){

if(animal instanceof Dog){

animal.bark();

}

}

Commonly used with classes.


37. What is the in operator?

Answer

Checks whether a property exists inside an object.

Example

type Admin={
permissions:string[];
};

type User={
name:string;
};

function check(
person:
Admin|User
){

if("permissions" in person){

console.log("Admin");

}else{

console.log("User");

}

}

Very common in interviews.


38. What are Type Assertions?

Answer

Type Assertion tells TypeScript

“Trust me—I know the type.”

Example

let value:any="Savanka";

let length=
(value as string)
.length;

Alternative syntax

let length=
(<string>value)
.length;

Warning

Type assertions don’t perform runtime conversion.


39. What are Classes in TypeScript?

Answer

Classes allow object-oriented programming.

Example

class Employee{

name:string;

constructor(name:string){

this.name=name;

}

greet(){

console.log(
"Welcome " +
this.name
);

}

}

Usage

const emp=
new Employee(
"Sagar"
);

emp.greet();

Benefits

  • Encapsulation
  • Reusability
  • Inheritance

40. What are Access Modifiers?

Answer

Access modifiers control property visibility.

ModifierAccessible
publicEverywhere
privateInside class only
protectedClass + Child classes

Example

class Employee{

public name="Sagar";

private salary=50000;

protected company=
"Savanka";

}

Trying to access

emp.salary;

Results in

Property 'salary' is private.

Interview Tip

Many Angular interviews ask:

Difference between private and protected?

private

Accessible only inside the same class.

protected

Accessible inside the class and inherited child classes.

41. What is Inheritance in TypeScript?

Answer

Inheritance is an Object-Oriented Programming (OOP) concept that allows one class to inherit the properties and methods of another class using the extends keyword. It promotes code reusability and helps reduce duplication.

Example

class Person {
  constructor(public name: string) {}

  introduce() {
    console.log(`Hi, I'm ${this.name}`);
  }
}

class Employee extends Person {
  constructor(name: string, public department: string) {
    super(name);
  }

  work() {
    console.log(`${this.name} works in ${this.department}`);
  }
}

const emp = new Employee("Sagar", "Engineering");
emp.introduce();
emp.work();

Output

Hi, I'm Sagar
Sagar works in Engineering

Interview Tip

Explain that inheritance represents an “is-a” relationship.

Example:

  • Dog is an Animal.
  • Employee is a Person.

42. What is the super keyword?

Answer

The super keyword refers to the parent class. It is mainly used to:

  • Call the parent constructor.
  • Access parent methods.

Example

class Animal {
  constructor(public name: string) {}

  eat() {
    console.log(`${this.name} is eating`);
  }
}

class Dog extends Animal {
  constructor(name: string) {
    super(name);
  }

  bark() {
    console.log("Woof!");
  }
}

const dog = new Dog("Bruno");
dog.eat();
dog.bark();

Why use super?

Without calling super(), the child class cannot access the parent class constructor.


43. What is an Abstract Class?

Answer

An abstract class is a class that cannot be instantiated directly. It is used as a base class for other classes.

Abstract classes may contain:

  • Abstract methods (must be implemented by child classes).
  • Concrete methods (already implemented).

Example

abstract class Shape {
  abstract area(): number;

  display() {
    console.log("Calculating area...");
  }
}

class Circle extends Shape {
  constructor(private radius: number) {
    super();
  }

  area(): number {
    return Math.PI * this.radius * this.radius;
  }
}

const circle = new Circle(5);

circle.display();
console.log(circle.area());

Interview Tip

An abstract class can contain both implemented and unimplemented methods.


44. Interface vs Abstract Class

InterfaceAbstract Class
Defines only a contractDefines contract + implementation
No constructorsCan have constructors
No stateCan maintain state
Supports multiple implementationsOnly single inheritance

When to use Interface?

  • API contracts
  • DTOs
  • Object shapes

When to use Abstract Class?

  • Shared business logic
  • Base functionality
  • Code reuse

45. What is Function Overloading?

Answer

Function overloading allows multiple function signatures with a single implementation.

Example

function add(a: number, b: number): number;
function add(a: string, b: string): string;

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

console.log(add(10, 20));

console.log(add("Hello ", "World"));

Output

30

Hello World

Interview Tip

TypeScript only allows one implementation, even if there are multiple signatures.


46. What are Modules?

Answer

Modules help organize code into reusable files.

Export

export function greet() {
  console.log("Hello");
}

Import

import { greet } from "./utils";

greet();

Benefits

  • Reusable code
  • Better maintainability
  • Encapsulation
  • Easier testing

47. What are Namespaces?

Answer

Namespaces group related code under a single name.

Example

namespace EmployeeModule {
  export function display() {
    console.log("Employee Module");
  }
}

EmployeeModule.display();

Interview Tip

Namespaces are rarely used in modern applications because ES Modules have become the standard.


48. What are Decorators?

Answer

Decorators are special functions that add metadata or modify the behavior of classes, methods, properties, or parameters.

Angular heavily relies on decorators.

Example

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html'
})

export class HomeComponent {

}

Other examples include:

  • @Injectable
  • @Input
  • @Output
  • @HostListener
  • @Pipe

Interview Tip

If you’re interviewing for Angular, decorators are one of the most commonly asked TypeScript-related topics.


49. What is Async/Await?

Answer

async and await simplify asynchronous programming by making asynchronous code look synchronous.

Example

async function fetchUsers() {

    const response = await fetch('/api/users');

    const users = await response.json();

    console.log(users);

}

fetchUsers();

Advantages

  • Cleaner code
  • Easier debugging
  • Better readability
  • Avoids callback hell

50. What are Promises?

Answer

A Promise represents the eventual completion (or failure) of an asynchronous operation.

States

  • Pending
  • Fulfilled
  • Rejected

Example

const promise = new Promise<string>((resolve, reject) => {

    resolve("Success");

});

promise.then(result => {

    console.log(result);

});

Interview Tip

Most developers prefer async/await, but it’s important to understand that it is built on top of Promises.


51. What are Conditional Types?

Answer

Conditional types allow you to choose one type or another based on a condition.

Syntax

T extends U ? X : Y

Example

type IsString<T> = T extends string ? true : false;

type A = IsString<string>;

type B = IsString<number>;

Result

A = true

B = false

Why use Conditional Types?

They make generic code more flexible and expressive.


52. What is the infer keyword?

Answer

The infer keyword extracts a type from another type.

Example

type ReturnType<T> =
    T extends (...args: any[]) => infer R
        ? R
        : never;

Usage

function greet() {

    return "Hello";

}

type Result = ReturnType<typeof greet>;

Result

string

Interview Tip

The infer keyword is often used when creating custom utility types.


53. What are Template Literal Types?

Answer

Template Literal Types allow you to build new string types using template literals.

Example

type Direction = "top" | "bottom";

type Position = `${Direction}-left`;

Result

"top-left"

"bottom-left"

Real-world Uses

  • CSS utility classes
  • API route names
  • Event names
  • Dynamic keys

54. What are Indexed Access Types?

Answer

Indexed Access Types retrieve the type of a property from another type.

Example

interface User {

    id: number;

    name: string;

}

type UserName = User["name"];

Result

string

Useful when reusing existing types without duplication.


55. What are Recursive Types?

Answer

Recursive Types reference themselves.

Example

interface TreeNode {

    value: string;

    children?: TreeNode[];

}

Useful for:

  • Tree structures
  • Menus
  • Comments
  • Categories
  • File systems

56. What is Declaration Merging?

Answer

TypeScript allows multiple interface declarations with the same name to merge automatically.

Example

interface User {

    name: string;

}

interface User {

    age: number;

}

Result

interface User {

    name: string;

    age: number;

}

Interview Tip

Declaration merging works with interfaces, but not with type aliases.


57. What are Declaration Files (.d.ts)?

Answer

Declaration files describe the shape of JavaScript libraries without providing an implementation.

Example

declare function greet(name: string): void;

Common uses include:

  • Third-party libraries
  • JavaScript packages
  • Type definitions

58. What is tsconfig.json?

Answer

tsconfig.json is the configuration file for the TypeScript compiler.

Example

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "strict": true,
    "outDir": "./dist"
  }
}

Common Compiler Options

  • target
  • module
  • strict
  • outDir
  • rootDir
  • baseUrl
  • paths
  • sourceMap

Interview Tip

Most Angular projects automatically generate a tsconfig.json file.


59. What is Strict Mode?

Answer

Strict Mode enables stricter type checking and catches more errors during compilation.

Example

{
  "strict": true
}

Strict mode includes checks such as:

  • noImplicitAny
  • strictNullChecks
  • strictFunctionTypes
  • strictPropertyInitialization

Benefits

  • Fewer runtime bugs
  • Better code quality
  • Safer refactoring

60. What is noImplicitAny?

Answer

When enabled, TypeScript reports an error if it cannot infer a type and would otherwise use any.

Example

function add(a, b) {

    return a + b;

}

Compiler Error

Parameter 'a' implicitly has an 'any' type.

Correct Version

function add(a: number, b: number): number {

    return a + b;

}

Interview Tip

noImplicitAny is considered one of the most important compiler options for maintaining a type-safe codebase.

61. What is exactOptionalPropertyTypes?

Answer

By default, an optional property (?) can either be missing or explicitly set to undefined.

When exactOptionalPropertyTypes is enabled, TypeScript treats these cases differently, making optional properties more precise.

Example

interface User {
    name?: string;
}

Without exactOptionalPropertyTypes

const user: User = {
    name: undefined
};

Allowed.

With

{
    "compilerOptions": {
        "exactOptionalPropertyTypes": true
    }
}

This assignment becomes invalid unless the property type explicitly includes undefined.

Interview Tip

This option is useful in large applications where the distinction between missing and undefined matters.


62. What is Module Resolution?

Answer

Module Resolution is the process TypeScript uses to locate imported files.

Example

import { UserService } from "./services/user.service";

TypeScript searches for:

  • user.service.ts
  • user.service.tsx
  • index.ts
  • Installed packages in node_modules

Types of Module Resolution

  • Node
  • Classic

Modern projects almost always use Node resolution.


63. What is Path Mapping?

Answer

Path Mapping allows you to create aliases instead of long relative import paths.

Instead of

import { AuthService } from "../../../services/auth.service";

Use

import { AuthService } from "@services/auth.service";

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@services/*": ["app/services/*"]
    }
  }
}

Benefits

  • Cleaner imports
  • Easier refactoring
  • Better project organization

64. ESM vs CommonJS

Answer

TypeScript supports both module systems.

ES Modules (Modern)

export function greet() {}

import { greet } from "./utils";

CommonJS

module.exports = greet;

const greet = require("./utils");

Comparison

ES ModulesCommonJS
import/exportrequire/module.exports
StaticDynamic
Modern standardOlder Node.js style

Interview Tip

Angular uses ES Modules.


65. What are Source Maps?

Answer

Source Maps allow developers to debug the original TypeScript code instead of the compiled JavaScript.

tsconfig.json

{
  "compilerOptions": {
    "sourceMap": true
  }
}

Benefits

  • Easier debugging
  • Better stack traces
  • Improved developer experience

66. What is Type Narrowing?

Answer

Type Narrowing reduces a union type to a more specific type based on runtime checks.

Example

function print(value: string | number) {

    if (typeof value === "string") {

        console.log(value.toUpperCase());

    } else {

        console.log(value.toFixed(2));

    }

}

Common Narrowing Techniques

  • typeof
  • instanceof
  • in
  • Equality checks
  • Custom type guards

67. What are Discriminated Unions?

Answer

Discriminated Unions use a common property to distinguish between different object types.

Example

interface Circle {

    type: "circle";

    radius: number;

}

interface Rectangle {

    type: "rectangle";

    width: number;

    height: number;

}

type Shape = Circle | Rectangle;

Usage

function area(shape: Shape) {

    switch (shape.type) {

        case "circle":

            return Math.PI * shape.radius ** 2;

        case "rectangle":

            return shape.width * shape.height;

    }

}

Interview Tip

Discriminated unions are commonly used in Redux reducers and Angular state management.


68. What is ReadonlyArray?

Answer

A ReadonlyArray prevents modification of an array after creation.

Example

const users: ReadonlyArray<string> = [

    "Sagar",

    "Rahul"

];

Invalid

users.push("Aman");

Compiler Error.

Why use it?

  • Prevent accidental mutations
  • Safer state management
  • Better functional programming

69. What are const Assertions?

Answer

A const assertion tells TypeScript to infer the narrowest possible type.

Example

const role = "admin" as const;

Type

"admin"

instead of

string

Useful for

  • API constants
  • Redux actions
  • Configuration objects

70. What is the satisfies operator?

Answer

Introduced in TypeScript 4.9, the satisfies operator checks that a value matches a type without changing the inferred type.

Example

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

const user = {
  name: "Sagar",
  age: 26
} satisfies User;

Benefits

  • Better inference
  • Strong validation
  • Prevents unnecessary type widening

71. What are Variadic Tuples?

Answer

Variadic Tuples allow tuples to have flexible lengths while preserving type information.

Example

type Numbers = [number, ...number[]];

const values: Numbers = [1, 2, 3, 4];

Use Cases

  • Function arguments
  • Middleware
  • Event emitters

72. What is Optional Chaining?

Answer

Optional Chaining (?.) safely accesses nested properties without throwing an error if an intermediate value is null or undefined.

Example

const city = user?.address?.city;

Without Optional Chaining

const city = user.address.city;

This would throw an error if address is undefined.

Benefits

  • Cleaner code
  • Fewer runtime errors
  • Easier null handling

73. What is Nullish Coalescing?

Answer

The Nullish Coalescing operator (??) returns the right-hand value only when the left-hand value is null or undefined.

Example

const username = input ?? "Guest";

Difference Between || and ??

const count = 0;

console.log(count || 10);

Output

10

Using ??

console.log(count ?? 10);

Output

0

Interview Tip

Use ?? when values like 0, false, or an empty string are valid and should not trigger the default value.


74. What are Index Signatures?

Answer

Index Signatures allow objects to have dynamic property names.

Example

interface Scores {

    [student: string]: number;

}

const marks: Scores = {

    Rahul: 90,

    Aman: 95

};

Use Cases

  • Dictionaries
  • Lookup tables
  • Configuration objects

75. What is the symbol type?

Answer

A symbol is a primitive type that creates unique identifiers.

Example

const id = Symbol("id");

const user = {

    [id]: 101,

    name: "Sagar"

};

Why use Symbols?

  • Unique object keys
  • Prevent property name collisions
  • Hide internal implementation details

76. What is bigint?

Answer

bigint represents integers larger than Number.MAX_SAFE_INTEGER.

Example

const amount = 9007199254740995n;

Why use BigInt?

  • Financial calculations
  • Scientific computations
  • Large database IDs
  • Cryptography

77. How can you improve TypeScript performance?

Answer

Some best practices include:

  • Enable incremental compilation.
  • Use project references for large applications.
  • Avoid unnecessary any types.
  • Split large files into smaller modules.
  • Enable strict mode.
  • Use path mapping.
  • Remove unused code.

Interview Tip

Performance improvements are usually related to compile time and developer experience, not runtime speed.


78. What are TypeScript Best Practices?

Answer

Some widely recommended best practices are:

  • Prefer unknown over any.
  • Enable strict mode.
  • Use interfaces for object shapes.
  • Use utility types where appropriate.
  • Keep types small and reusable.
  • Avoid duplicated type definitions.
  • Use descriptive type names.
  • Favor composition over inheritance when possible.

79. What are some Common TypeScript Errors?

Answer

Common compiler errors include:

Type mismatch

let age: number = "25";

Property does not exist

user.salary;

Implicit any

function add(a, b) {}

Object missing required property

interface User {

    name: string;

}

const user: User = {};

Interview Tip

Be comfortable reading compiler error messages—they often tell you exactly what’s wrong.


80. How do you Debug TypeScript Applications?

Answer

Common debugging techniques include:

  • Use browser DevTools with source maps.
  • Debug directly in VS Code.
  • Inspect generated JavaScript when necessary.
  • Enable strict compiler options.
  • Use logging strategically.
  • Write unit tests for complex logic.

Recommended Tools

  • VS Code Debugger
  • Chrome DevTools
  • Angular DevTools
  • Jest
  • Vitest

⭐ Quick Revision (Questions 61–80)

You now understand:

  • exactOptionalPropertyTypes
  • ✅ Module Resolution
  • ✅ Path Mapping
  • ✅ ES Modules vs CommonJS
  • ✅ Source Maps
  • ✅ Type Narrowing
  • ✅ Discriminated Unions
  • ReadonlyArray
  • const Assertions
  • satisfies Operator
  • ✅ Variadic Tuples
  • ✅ Optional Chaining
  • ✅ Nullish Coalescing
  • ✅ Index Signatures
  • symbol
  • bigint
  • ✅ TypeScript Performance
  • ✅ Best Practices
  • ✅ Common Compiler Errors
  • ✅ Debugging TypeScript

81. How would you create a type-safe REST API response?

Answer

When working with REST APIs, it’s a good practice to define interfaces for API responses instead of using any.

Example

interface ApiResponse<T> {
    success: boolean;
    message: string;
    data: T;
}

interface User {
    id: number;
    name: string;
    email: string;
}

const response: ApiResponse<User> = {
    success: true,
    message: "User fetched successfully",
    data: {
        id: 1,
        name: "Sagar",
        email: "sagar@example.com"
    }
};

Why is this better?

  • Compile-time type safety
  • Better IntelliSense
  • Reusable structure
  • Fewer runtime errors

Interview Tip

Always use generics for API responses instead of duplicating interfaces.


82. How would you type React component props?

Answer

Props should always be strongly typed.

Example

interface ButtonProps {
    title: string;
    disabled?: boolean;
    onClick: () => void;
}

function Button({
    title,
    disabled,
    onClick
}: ButtonProps) {

    return (
        <button
            disabled={disabled}
            onClick={onClick}
        >
            {title}
        </button>
    );
}

Benefits

  • Auto-completion
  • Compile-time validation
  • Better maintainability

83. How do you use TypeScript in Angular Services?

Answer

Angular services benefit from strongly typed models and HTTP responses.

Example

interface User {
    id: number;
    name: string;
}

@Injectable({
    providedIn: 'root'
})
export class UserService {

    constructor(private http: HttpClient) {}

    getUsers() {
        return this.http.get<User[]>('/api/users');
    }

}

Interview Tip

Avoid returning Observable<any> whenever possible.

Prefer

Observable<User[]>

84. How would you define DTOs (Data Transfer Objects)?

Answer

DTOs represent data exchanged between the client and server.

Example

interface CreateUserDto {

    name: string;

    email: string;

    password: string;

}

Update DTO

interface UpdateUserDto {

    name?: string;

    email?: string;

}

Benefits

  • Validation
  • Clear API contracts
  • Better documentation

85. How would you implement a Generic Repository?

Answer

Generic repositories reduce duplicated CRUD logic.

Example

interface Repository<T> {

    getAll(): Promise<T[]>;

    getById(id: number): Promise<T>;

    create(item: T): Promise<T>;

    update(item: T): Promise<T>;

    delete(id: number): Promise<void>;

}

Example

class UserRepository
implements Repository<User>{

// Implementation

}

Why use Generic Repositories?

  • Reusability
  • Cleaner architecture
  • Easier testing

86. How do you validate API responses?

Answer

Never assume an API always returns valid data.

Example

if(response.success){

console.log(response.data);

}

Libraries

  • Zod
  • io-ts
  • Yup

These libraries validate runtime data because TypeScript types disappear after compilation.


87. Explain Dependency Injection with TypeScript.

Answer

Dependency Injection (DI) allows objects to receive dependencies rather than creating them.

Angular example

constructor(
private userService:UserService
){}

Benefits

  • Loose coupling
  • Easier testing
  • Better architecture

88. How would you design a reusable Generic Service?

Example

class ApiService<T>{

getAll(){

}

create(item:T){

}

update(item:T){

}

delete(id:number){

}

}

Usage

const service=
new ApiService<User>();

Very common in enterprise applications.


89. How do you avoid using any in large applications?

Best Practices

  • Use Interfaces
  • Use Generics
  • Use Unknown
  • Use Utility Types
  • Enable Strict Mode
  • Create reusable models
  • Use API DTOs

Interview Tip

Large companies rarely allow unrestricted any.


90. What are some common TypeScript design patterns?

Examples

  • Singleton
  • Factory
  • Observer
  • Strategy
  • Repository
  • Builder
  • Adapter

These patterns improve scalability and maintainability.


91. Scenario: API returns different response types. How would you handle it?

Example

interface Success {

status:"success";

data:string;

}

interface Error{

status:"error";

message:string;

}

type ApiResult=
Success|Error;

Usage

if(result.status==="success"){

console.log(result.data);

}else{

console.log(result.message);

}

This is a perfect use case for Discriminated Unions.


92. Scenario: Build a reusable Table Component.

Solution

Use Generics.

Example

interface TableProps<T>{

data:T[];

}

Now the table works with

  • Users
  • Products
  • Orders
  • Employees

without rewriting code.


93. Scenario: User roles

Instead of

let role:string;

Use

type Role=
"Admin"|
"User"|
"Guest";

Benefits

  • Prevent invalid values
  • Better auto-completion
  • Cleaner code

94. Scenario: Shopping Cart

Define interfaces.

interface Product{

id:number;

name:string;

price:number;

quantity:number;

}

Benefits

  • Strong typing
  • Better maintainability

95. Scenario: Form Validation

Example

interface LoginForm{

email:string;

password:string;

}

Validation becomes much easier because every field has a known type.


96. Scenario: Building a Configuration Object

Use Readonly.

interface Config{

readonly apiUrl:string;

readonly version:string;

}

Configuration cannot accidentally change during runtime.


97. Scenario: Dynamic Object Keys

Use Index Signatures.

interface Languages{

[key:string]:string;

}

Example

const languages={

en:"English",

fr:"French"

}

98. Scenario: Type-safe Event System

Example

interface Events{

login:string;

logout:string;

signup:string;

}

Use

type EventName=
keyof Events;

Now only valid event names are allowed.


99. Scenario: Large Enterprise Application

Recommended architecture

Models

DTOs

Services

Repositories

Interfaces

Utility Types

Strict Mode

Generic APIs

This improves

  • Scalability
  • Maintainability
  • Testing
  • Collaboration

100. What are the most important TypeScript topics to master for interviews?

Beginner

  • Types
  • Interfaces
  • Functions
  • Classes
  • Enums
  • Arrays
  • Objects

Intermediate

  • Generics
  • Utility Types
  • Type Guards
  • Modules
  • Access Modifiers
  • Async Programming

Advanced

  • Conditional Types
  • Infer
  • Mapped Types
  • Declaration Files
  • Compiler Options
  • Advanced Generics
  • Performance
  • Architecture

Interview Tip

Don’t memorize definitions. Instead:

  • Build real projects.
  • Explain your thought process.
  • Understand why TypeScript features exist.
  • Practice debugging compiler errors.
  • Be ready to discuss trade-offs and best practices.

Frequently Asked Questions (FAQs)

Is TypeScript difficult to learn?

No. If you’re comfortable with JavaScript, learning TypeScript is straightforward. Start with basic types and interfaces, then move on to generics, utility types, and advanced features.


Do all Angular developers need TypeScript?

Yes. Angular is built with TypeScript and uses its features extensively, including decorators, interfaces, generics, and strong typing.


Is TypeScript useful for React?

Absolutely. TypeScript improves React development by providing type-safe props, state management, hooks, and API interactions.


Can TypeScript replace JavaScript?

No. TypeScript compiles into JavaScript, so JavaScript remains the language that browsers and Node.js execute.


Which TypeScript topics are asked most frequently?

Interviewers commonly focus on:

  • Interfaces vs Type Aliases
  • Generics
  • Utility Types
  • any vs unknown
  • Type Guards
  • Classes
  • Access Modifiers
  • Async/Await
  • Conditional Types
  • Compiler Options

Final Interview Tips

Before your interview:

  • Revise JavaScript fundamentals alongside TypeScript.
  • Write code every day instead of only reading theory.
  • Build small projects using Angular, React, or Node.js.
  • Practice explaining concepts aloud.
  • Understand compiler errors and how to fix them.
  • Review real-world scenarios such as API design, DTOs, and reusable components.
  • Stay updated with the latest TypeScript features.

Conclusion

TypeScript has become the standard for building scalable JavaScript applications. Whether you’re developing Angular applications, React frontends, or Node.js backends, a strong understanding of TypeScript can significantly improve code quality, maintainability, and developer productivity.

By mastering the 100 interview questions covered in this guide and practicing them with real-world projects, you’ll be well-prepared for technical interviews ranging from junior to senior software engineering roles.

Good luck with your interview preparation!

Explore More

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *