76 Topics
Chapter•600 Minutes

Complete TypeScript Interview Questions & Answer Bank

75+ curated TypeScript interview questions covering core type primitives, structural typing, generics, utility types, mapped types, advanced type inference, decorators, and compiler optimization.

Q1: What is TypeScript and what are its core advantages over plain JavaScript?

Difficulty:EasyTopic:Fundamentals

TypeScript is a strongly typed, open-source programming language developed by Microsoft that builds on JavaScript by adding syntactical type declarations.

Core Advantages

  • Static Type Checking: Catches errors at compile time rather than runtime.
  • Enhanced IDE Support: Enables intelligent autocompletion, refactoring, and code navigation.
  • Downlevel Compilation: Transpiles modern ECMAScript features down to older ES versions (ES5/ES3).
  • Explicit Self-Documenting Code: Interfaces and type aliases act as living documentation.
Key Takeaways
  • TypeScript is a strict syntactical superset of JavaScript.

  • All valid JavaScript code is valid TypeScript code.

Q2: What is Structural Typing (Duck Typing) and how does it differ from Nominal Typing?

Difficulty:EasyTopic:Type System

TypeScript uses a Structural Type System. Types are evaluated solely by their shape or structure (the properties and methods they possess), rather than their explicit declaration name or inheritance chain.

In Nominal Type Systems (like Java or C#), two objects with identical properties are not interchangeable unless they explicitly inherit from the same named class or interface.

Structural Compatibility Example
interface Point2D { x: number; y: number; }
interface Vector2D { x: number; y: number; }

const logPoint = (p: Point2D) => console.log(`${p.x}, ${p.y}`);
const velocity: Vector2D = { x: 10, y: 20 };

logPoint(velocity); // Valid! Vector2D matches the structure of Point2D.

Even though velocity is typed as Vector2D, TypeScript accepts it because its internal structure matches Point2D.

Key Takeaways
  • TypeScript checks structure, not explicit declaration names.

  • If an object has the required fields with matching types, TypeScript considers it compatible.

Q3: What are the primitive types available in TypeScript?

Difficulty:EasyTopic:Primitives

TypeScript supports all native JavaScript primitives alongside type additions:

  • string: Textual data.
  • number: Floating-point numbers and integers.
  • boolean: True/false values.
  • bigint: Large integers beyond $2^{53} - 1$.
  • symbol: Unique, immutable identifiers.
  • null & undefined: Absence of value or uninitialized state.
  • void: Signals absence of return value from functions.
Key Takeaways
  • Primitive types in TypeScript correspond directly to JavaScript's runtime primitive types.

  • Always use lowercase primitive names (string, number) rather than wrapper objects (String, Number).

Q4: What is the difference between `any` and `unknown` types?

Difficulty:EasyTopic:Type Safety

any disables type checking entirely, turning off compile-time safety. You can access arbitrary properties, call them as functions, or assign them to any target type.

unknown is the type-safe counterpart of any. It represents any value, but TypeScript prevents you from performing arbitrary operations on an unknown variable until you perform explicit type checking or narrowing.

any vs unknown Behavior
let valueAny: any = "hello";
valueAny.foo.bar(); // Compiles fine, runtime crash!

let valueUnknown: unknown = "hello";
// valueUnknown.trim(); // Error: Object is of type 'unknown'.

if (typeof valueUnknown === "string") {
  console.log(valueUnknown.trim()); // Valid! Narrowed safely.
}

unknown forces developer verification before property access, preventing accidental runtime exceptions.

Key Takeaways
  • Prefer unknown over any when working with dynamic or unexpected values.

  • unknown requires explicit narrowing before property access.

Q5: What is the `never` type and how is it used for exhaustive type checking?

Difficulty:MediumTopic:Advanced Types

The never type represents values that never occur. It represents the return type of functions that never finish (e.g., throwing an error or running an infinite loop).

Because never is a assignable to every type, but no type is assignable to never (except never itself), it is used to perform Exhaustive Type Checking inside switch statements.

Exhaustive Switch-Case Checking
type Shape = { kind: 'circle' } | { kind: 'square' };

function getArea(s: Shape): number {
  switch (s.kind) {
    case 'circle': return Math.PI * 2;
    case 'square': return 4;
    default:
      const _exhaustiveCheck: never = s;
      return _exhaustiveCheck;
  }
}

If a developer adds a new union member to Shape without handling it in the switch statement, TypeScript raises a compile-time error.

Key Takeaways
  • never signals unreachable code paths.

  • Assigning unhandled union cases to never guarantees total compile-time switch coverage.

Q6: What is the difference between `type` aliases and `interface` declarations?

Difficulty:EasyTopic:Core Concepts

Both type and interface define structural contracts, but they differ in capabilities:

Interface vs Type Alias Comparison

Declaration Merging

Supported by interface | Unsupported by type

Multiple interface declarations with the same name automatically merge properties.

Union & Primitives

Unsupported by interface | Supported by type

Type aliases can define unions (A | B), primitives, tuples, and mapped types directly.

Extensibility

extends keyword vs Intersection (&)

Interfaces extend other interfaces; types create intersections.

Key Takeaways
  • Use interface for public API contracts and object structures that benefit from declaration merging.

  • Use type for union types, tuples, primitives, and complex mapped/conditional types.

Q7: What is the difference between Union Types (`|`) and Intersection Types (`&`)?

Difficulty:EasyTopic:Type Combinations
  • Union Type (A | B): Represents a value that can be either type A or type B. You can only access properties common to both types unless narrowed.
  • Intersection Type (A & B): Combines multiple type structures into one. The resulting value must satisfy both type contracts simultaneously.
Union vs Intersection
type Admin = { name: string; permissions: string[] };
type User = { name: string; email: string };

// Union: Must be Admin OR User
type Account = Admin | User;

// Intersection: Must have ALL properties from Admin AND User
type SuperAdmin = Admin & User;

Intersection types merge structural constraints, requiring all combined properties.

Key Takeaways
  • Unions allow one of several types; Intersections merge multiple types into one.

Q8: What are Literal Types and how do `as const` assertions work?

Difficulty:MediumTopic:Literals

Literal types restrict variables to exact concrete values (strings, numbers, or booleans) rather than wider primitive categories.

A const assertion (as const) instructs TypeScript to infer the narrowest possible literal types for object properties and arrays, turning properties into readonly fields.

as const Assertion
// Standard object inference
const config = {
  endpoint: "/api",
  retries: 3
}; // Type: { endpoint: string; retries: number; }

// const assertion
const constConfig = {
  endpoint: "/api",
  retries: 3
} as const; // Type: { readonly endpoint: "/api"; readonly retries: 3; }

as const prevents property widening and marks array/object members read-only.

Key Takeaways
  • Literal types lock values to exact concrete constants.

  • as const creates deeply immutable readonly literal data types.

Q9: What are Tuple Types in TypeScript and how do Readonly Tuples work?

Difficulty:EasyTopic:Data Structures

A Tuple is a fixed-length array where every element index has an explicitly declared type.

Standard tuples permit mutable array operations like .push(), which can bypass tuple index checks. Wrapping tuples with readonly enforces strict immutability.

Tuple and Readonly Tuple
type ResponseState = [code: number, message: string];
const state: ResponseState = [200, "OK"];

type ImmutableState = readonly [number, string];
const fixed: ImmutableState = [404, "Not Found"];
// fixed.push("error"); // Error: Property 'push' does not exist on type 'readonly [number, string]'

Readonly tuples block array mutation methods like push, pop, or index modification.

Key Takeaways
  • Tuples lock array element types to explicit index positions.

  • Use readonly on tuples to block accidental array mutations.

Q10: What are Enums, String Enums, and `const enum` declarations?

Difficulty:MediumTopic:Enums

Enums allow defining named sets of constants. TypeScript supports Numeric, String, and const enums.

Standard enums generate runtime JavaScript objects. A const enum is completely removed during compilation—its values are directly inlined into call sites, leaving zero JavaScript runtime object footprint.

const enum Inlining
const enum Direction {
  Up = "UP",
  Down = "DOWN"
}

const move = Direction.Up;
// Compiled JS output:
// var move = "UP"; // No Enum object generated!

const enum inlines literal values directly at compile time, reducing JavaScript bundle size.

Key Takeaways
  • Use const enum to eliminate runtime JavaScript object overhead.

  • String enums offer better readability during debugging than numeric enums.

Q11: What is Type Narrowing and how do build-in Type Guards work?

Difficulty:EasyTopic:Type Guarding

Type Narrowing is the process where TypeScript refines a broad type (like a union) into a narrower type within a specific code block using logical checks.

Native Guards

  • typeof: Narrow primitive types (string, number, boolean, symbol).
  • instanceof: Narrow class instances.
  • in operator: Check if a property key exists on an object.
  • Truthiness checks (if (val)): Exclude null or undefined.
Key Takeaways
  • Type narrowing leverages standard JavaScript logical conditional checks.

  • TypeScript inspects execution branches to refine types automatically.

Q12: What are User-Defined Type Guards using custom Type Predicates (`value is T`)?

Difficulty:MediumTopic:Type Guarding

A User-Defined Type Guard is a function whose return type signature uses a Type Predicate in the form parameterName is Type.

When the function returns true, TypeScript narrow the argument's type in the calling conditional block.

Custom Type Guard Function
interface Fish { swim: () => void }
interface Bird { fly: () => void }

// Custom Type Guard
function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

function move(pet: Fish | Bird) {
  if (isFish(pet)) {
    pet.swim(); // Narrowed safely to Fish
  } else {
    pet.fly();  // Narrowed safely to Bird
  }
}

The pet is Fish predicate instructs TypeScript to treat pet as Fish inside the true branch.

Key Takeaways
  • Type predicates (arg is T) allow custom type narrowing logic.

  • Used to encapsulate custom type-validation runtime logic.

Q13: What are Assertion Functions using the `asserts` keyword?

Difficulty:MediumTopic:Type Guarding

Assertion functions throw an error if a condition check fails. They use the return signature asserts condition or asserts val is T to instruct TypeScript that if the function returns normally without throwing, the asserted type assumption holds true for remaining code execution.

Assertion Function Pattern
function assertIsString(val: unknown): asserts val is string {
  if (typeof val !== "string") {
    throw new Error("Not a string!");
  }
}

function processInput(input: unknown) {
  assertIsString(input);
  // input is now safely narrowed to string for all following lines
  console.log(input.toUpperCase());
}

If assertIsString completes without throwing an error, TypeScript narrow input to string for the remaining scope.

Key Takeaways
  • asserts narrowing stays active across subsequent lines without requiring an if block.

Q14: What are Discriminated Unions (Tagged Unions)?

Difficulty:EasyTopic:Type System

A Discriminated Union is a pattern where every type in a union shares a single common literal property (the discriminant tag). TypeScript uses this discriminant property to narrow down exact union members inside switch statements or conditional checks.

Discriminated Union Pattern
interface LoadingState { status: 'loading' }
interface SuccessState { status: 'success'; data: string }
interface ErrorState { status: 'error'; error: Error }

type NetworkState = LoadingState | SuccessState | ErrorState;

function handleState(state: NetworkState) {
  switch (state.status) { // status is the discriminant
    case 'success':
      return state.data; // Safely narrowed to SuccessState
    case 'error':
      return state.error.message; // Safely narrowed to ErrorState
  }
}

The shared status literal property allows TypeScript to narrow down the union type.

Key Takeaways
  • Use a shared literal property tag across members of a union.

  • Enables clean, type-safe conditional branching.

Q15: What is the Non-Null Assertion Operator (`!`) and when should it be avoided?

Difficulty:EasyTopic:Operators

The non-null assertion operator (postfix !) tells the TypeScript compiler to assert that an expression is neither null nor undefined, suppressing strict null checking errors.

It does not emit any runtime protective checks. If the value is null or undefined at runtime, your code will throw an unhandled exception.

Key Takeaways
  • The ! operator removes null and undefined from a type at compile time.

  • It generates no runtime JavaScript protective code—use it with caution.

Q16: How do Optional Chaining (`?.`) and Nullish Coalescing (`??`) work?

Difficulty:EasyTopic:Operators
  • Optional Chaining (?.): Safely accesses nested object properties or methods. If the left-hand operand is null or undefined, evaluation stops and returns undefined without throwing a TypeError.
  • Nullish Coalescing (??): A logical operator that returns its right-hand operand only when the left-hand operand evaluates to null or undefined (unlike ||, which triggers on all falsy values like 0 or "").
Key Takeaways
  • ?. prevents nested property access runtime errors.

  • ?? checks explicitly for null or undefined, ignoring falsy values like 0 or false.

Q17: What are Type Assertions (`as T`) and how do they differ from Type Casting?

Difficulty:EasyTopic:Type Assertions

Type Assertions instruct the compiler to treat a value as a specific type using the syntax val as T or <T>val.

Type assertions do not perform runtime conversion (casting). They are purely compile-time directives removed during compilation. To convert runtime types (e.g., string to number), you must call JavaScript conversion functions like Number(str).

Key Takeaways
  • Type assertions do not change runtime JavaScript data structures.

  • Use as unknown as TargetType for double assertions when types do not overlap.

Q18: What are Generics and why are they important?

Difficulty:MediumTopic:Generics

Generics allow you to write reusable, type-safe components that work across multiple data types rather than a single type, while preserving full static type safety.

Type parameters (conventionally written as <T>) act as type variables captured when functions, classes, or interfaces are invoked.

Generic Identity Function
function identity<T>(arg: T): T {
  return arg;
}

const str = identity<string>("hello"); // Type: string
const num = identity(42);               // Inferred automatically as number

Generics lock function input types to function output types dynamically.

Key Takeaways
  • Generics provide type-safe reusability without resorting to any.

  • TypeScript infers type parameters automatically based on argument values.

Q19: How do Generic Constraints using the `extends` keyword work?

Difficulty:MediumTopic:Generics

Generic Constraints restrict the set of types acceptable by a generic parameter using the <T extends Boundary> syntax. This ensures the passed type satisfies specific structural requirements.

Constraining Generics to Objects with Length
interface Lengthwise {
  length: number;
}

function logLength<T extends Lengthwise>(arg: T): T {
  console.log(arg.length); // Guaranteed to exist
  return arg;
}

logLength("hello"); // Valid (strings have length)
logLength([1, 2, 3]); // Valid (arrays have length)
// logLength(123);   // Error: number doesn't have a 'length' property

T extends Lengthwise guarantees that any type passed into T possesses a numeric length property.

Key Takeaways
  • Use extends to enforce required structural properties on generic type arguments.

Q20: How do Generic Parameter Defaults work?

Difficulty:MediumTopic:Generics

Similar to JavaScript function argument defaults, generic parameter defaults allow specifying fallback types using the <T = DefaultType> syntax when caller type arguments are omitted.

Generic Default Type Signature
interface ApiResponse<TData = { status: string }> {
  data: TData;
  statusCode: number;
}

// Uses default type { status: string }
const defaultRes: ApiResponse = { data: { status: "OK" }, statusCode: 200 };

// Overrides default type with custom user structure
const userRes: ApiResponse<{ name: string }> = {
  data: { name: "Alice" },
  statusCode: 200
};

If no generic parameter is explicitly passed, TypeScript defaults to TData = { status: string }.

Key Takeaways
  • Generic parameter defaults fall back gracefully when explicit type arguments are omitted.

Q21: What is the `keyof` operator and how is it used?

Difficulty:MediumTopic:Type Operators

The keyof operator produces a union of string or numeric literal types representing the key names of an object type.

keyof Operator Usage
interface User {
  id: number;
  name: string;
  email: string;
}

type UserKeys = keyof User; // Type: 'id' | 'name' | 'email'

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

K extends keyof T guarantees that the provided key argument exists on the target object type T.

Key Takeaways
  • keyof T returns a union of all property name keys belonging to type T.

Q22: What is the `typeof` operator in Type Contexts?

Difficulty:EasyTopic:Type Operators

In a type expression context, typeof refers to the TypeScript type of a variable or property value, allowing you to infer types directly from runtime variables without writing manual interfaces.

typeof Type Context Extraction
const defaultTheme = {
  color: "blue",
  fontSize: 14,
  isDark: false
};

// Extract type structure from runtime variable
type Theme = typeof defaultTheme;
// Resulting type: { color: string; fontSize: number; isDark: boolean; }

typeof converts runtime JavaScript object structures into static TypeScript types.

Key Takeaways
  • Use typeof in type contexts to derive static type contracts directly from runtime JavaScript values.

Q23: How do Indexed Access Types (`T[K]`) work?

Difficulty:MediumTopic:Type Lookup

An Indexed Access Type looks up specific sub-properties on another type using bracket notation syntax (Type[Key]).

Property Type Lookup
interface Order {
  id: string;
  customer: {
    name: string;
    address: { city: string };
  };
}

type CustomerType = Order["customer"]; // Type: { name: string; address: { city: string } }
type CityType = Order["customer"]["address"]["city"]; // Type: string

Bracket notation pulls property types from complex nested object structures.

Key Takeaways
  • Look up property types dynamically from existing structural contracts.

Q24: How do `Partial<T>` and `Required<T>` utility types work?

Difficulty:EasyTopic:Utility Types
  • Partial<T>: Constructs a type with all properties of T set to optional (?).
  • Required<T>: Constructs a type with all properties of T set to required (removes optional ? flags).
Partial and Required Implementation
interface Profile {
  name: string;
  age?: number;
}

type OptionalProfile = Partial<Profile>;   // { name?: string; age?: number; }
type MandatoryProfile = Required<Profile>; // { name: string; age: number; }

Partial makes all properties optional; Required makes all properties mandatory.

Key Takeaways
  • Partial is ideal for update payload signatures (patch).

  • Required guarantees optional fields are populated.

Q25: How do `Readonly<T>` and `Record<K, T>` utility types work?

Difficulty:EasyTopic:Utility Types
  • Readonly<T>: Sets all properties of T to readonly, preventing property re-assignment.
  • Record<Keys, Type>: Constructs an object type whose property keys are derived from Keys and whose values are of type Type.
Record Map Definition
type Page = 'home' | 'about' | 'contact';
interface PageInfo { title: string }

const navPages: Record<Page, PageInfo> = {
  home: { title: 'Home' },
  about: { title: 'About' },
  contact: { title: 'Contact' }
};

Record enforces that all listed key members exist in the target mapping dictionary object.

Key Takeaways
  • Use Record to construct strongly-typed dictionary maps.

Q26: How do `Pick<T, K>` and `Omit<T, K>` utility types work?

Difficulty:EasyTopic:Utility Types
  • Pick<T, Keys>: Constructs a type by picking a specific set of property keys from T.
  • Omit<T, Keys>: Constructs a type by removing a specific set of property keys from T.
Pick vs Omit
interface Article {
  id: number;
  title: string;
  content: string;
  author: string;
}

type ArticlePreview = Pick<Article, 'id' | 'title'>; // Contains ONLY id & title
type ArticleDraft = Omit<Article, 'id'>;            // Contains title, content, author

Pick creates a subset with selected keys; Omit creates a subset excluding specified keys.

Key Takeaways
  • Pick selects specific keys; Omit excludes specific keys.

Q27: How do `Exclude<T, U>`, `Extract<T, U>`, and `NonNullable<T>` work?

Difficulty:MediumTopic:Utility Types

These utility types operate over union types:

  • Exclude<Union, ExcludedMembers>: Removes matching members from a union.
  • Extract<Union, ExtractedMembers>: Keeps only matching members from a union.
  • NonNullable<T>: Excludes null and undefined from a union type.
Key Takeaways
  • Operate over union types via distributive conditional logic.

Q28: How do `ReturnType<T>` and `Parameters<T>` utility types work?

Difficulty:MediumTopic:Utility Types
  • ReturnType<FunctionType>: Extracts the return type of a function signature.
  • Parameters<FunctionType>: Extracts the parameter types of a function signature as a tuple.
Extracting Function Signatures
function createTask(title: string, priority: number) {
  return { id: Date.now(), title, priority };
}

type TaskReturn = ReturnType<typeof createTask>; // { id: number, title: string, priority: number }
type TaskParams = Parameters<typeof createTask>; // [title: string, priority: number]

Infer return and parameter types dynamically using ReturnType and Parameters.

Key Takeaways
  • Use ReturnType and Parameters to extract function signature types dynamically.

Q29: What are Conditional Types and how does the ternary syntax (`T extends U ? X : Y`) work?

Difficulty:MediumTopic:Conditional Types

Conditional types select one of two possible types based on a type relationship check, using a syntax similar to conditional ternary expressions:

T extends U ? TrueType : FalseType

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

type Test1 = IsString<string>;  // true
type Test2 = IsString<number>;  // false

If T is assignable to string, evaluate to true; otherwise evaluate to false.

Key Takeaways
  • Conditional types enable dynamic compile-time decision logic.

Q30: What are Distributive Conditional Types and how can distribution be disabled?

Difficulty:AdvancedTopic:Conditional Types

When conditional types act on a bare generic type parameter (T), they automatically distribute across union types.

For example, IsString<A | B> evaluates as IsString<A> | IsString<B>.

To disable distribution, wrap the generic type parameter in square brackets: [T] extends [U].

Disabling Distribution via Square Brackets
type ToArrayDistributive<T> = T extends any ? T[] : never;
type Distributed = ToArrayDistributive<string | number>; // string[] | number[]

type ToArrayNonDistributive<T> = [T] extends [any] ? T[] : never;
type NonDistributed = ToArrayNonDistributive<string | number>; // (string | number)[]

Wrapping T in tuple brackets prevents unions from splitting during evaluation.

Key Takeaways
  • Unwrapped type parameters distribute automatically across unions in conditional types.

  • Wrap type parameters in tuple brackets [T] to disable distribution.