Autocoder

TypeScript Interview Questions and Answers

Last updated 2026-11-19

TypeScript interviews assume you know JavaScript and test whether you can model data precisely with types: when to use an interface or a type alias, how generics keep functions reusable, how narrowing works and what the utility types do.

The answers below cover the fundamentals and the intermediate topics that come up in front-end and Node roles. Remember the key fact that interviewers like to hear: types are erased at compile time, so they never protect you from bad data at runtime unless you validate it.

LevelFresher to 4 years
FocusType system, generics, narrowing, utility types
CompilerTypeScript 5.x with strict enabled

What good answers include

Mention structural typing, type erasure and strict mode, and prefer unknown to any. When you show an example, include the failing line and the error TypeScript would give, since that proves you understand why the type exists.

Related topics

TypeScript builds on the language described in JavaScript interview questions, and class features connect to prototypes and inheritance. For component typing, see React interview questions and how to crack a frontend interview.

TypeScript Interview Questions and Answers: questions with worked answers

  1. 1

    What is TypeScript and why use it?

    easy

    TypeScript is a statically typed superset of JavaScript developed by Microsoft. It adds type annotations, interfaces, generics and enums, and a compiler that checks types and emits plain JavaScript. Benefits are catching mistakes before running the code, better editor autocomplete and refactoring, and self-documenting code in large teams. The cost is a build step and some annotation overhead.

  2. 2

    What is the difference between interface and type?

    easy

    Both describe object shapes and are mostly interchangeable. An interface can be extended with extends and merged by declaring it twice, which suits public APIs and class contracts. A type alias can name any type, including unions, intersections, tuples, primitives and mapped or conditional types, but cannot be reopened. Pick one convention per codebase, commonly interface for object shapes and type for everything else.

    typescript
    interface User { id: number; name: string }
    interface User { email?: string }          // declaration merging
    
    type Id = string | number;                 // only a type can alias a union
    type Admin = User & { role: "admin" };     // intersection
    const a: Admin = { id: 1, name: "A", role: "admin" };
  3. 3

    What is the difference between any, unknown and never?

    medium

    any turns off type checking for a value, so anything is allowed and errors slip through. unknown is the type-safe counterpart: it accepts any value but you must narrow it before using it. never is the type of values that never occur, such as the return type of a function that always throws, or the leftover case after exhaustive narrowing. Prefer unknown for untrusted input.

    typescript
    let a: any = "x";
    a.foo();                      // compiles, fails at runtime
    
    let u: unknown = "x";
    // u.toUpperCase();           // error: 'u' is of type 'unknown'
    if (typeof u === "string") u.toUpperCase();   // fine after narrowing
    
    function fail(msg: string): never { throw new Error(msg); }
  4. 4

    How do union types and type narrowing work?

    medium

    A union such as string | number allows either type, and you may only use members common to both until you narrow. Narrowing uses typeof, instanceof, the in operator, equality checks, truthiness and user-defined type guards. A discriminated union adds a literal tag property so the compiler narrows by checking the tag.

    typescript
    type Shape =
      | { kind: "circle"; r: number }
      | { kind: "rect"; w: number; h: number };
    
    function area(s: Shape): number {
      switch (s.kind) {
        case "circle": return Math.PI * s.r ** 2;
        case "rect":   return s.w * s.h;
      }
    }
  5. 5

    How do you make a switch exhaustive with never?

    hard

    Assign the narrowed value to a variable of type never in the default branch. If a new member is later added to the union and not handled, the value is no longer never, and the compiler reports an error at that line. It converts a runtime omission into a compile-time failure.

    typescript
    type Status = "idle" | "loading" | "done";
    function label(s: Status): string {
      switch (s) {
        case "idle": return "Idle";
        case "loading": return "Loading";
        case "done": return "Done";
        default: {
          const _exhaustive: never = s;
          return _exhaustive;
        }
      }
    }
  6. 6

    What are generics, and why are they useful?

    medium

    Generics let a function, class or type work with a type chosen by the caller, keeping the link between input and output types instead of falling back to any. A type parameter can be constrained with extends so you may use certain properties inside. The compiler usually infers the argument.

    typescript
    function first<T>(items: T[]): T | undefined {
      return items[0];
    }
    const n = first([1, 2, 3]);        // number | undefined
    const s = first(["a"]);            // string | undefined
    
    function pluck<T, K extends keyof T>(o: T, k: K): T[K] { return o[k]; }
    const name = pluck({ name: "A", age: 3 }, "name");   // string
  7. 7

    List the common utility types and what they do.

    medium

    Partial makes all properties optional, Required makes all required, Readonly makes them read-only, Pick selects some keys, Omit removes some keys, Record builds an object type from a key type and value type, Exclude and Extract filter unions, NonNullable removes null and undefined, ReturnType and Parameters extract function types, and Awaited unwraps promises.

    typescript
    interface User { id: number; name: string; email: string }
    type Draft = Partial<User>;
    type Preview = Pick<User, "id" | "name">;
    type NoEmail = Omit<User, "email">;
    type Roles = Record<"admin" | "guest", boolean>;
    type R = ReturnType<typeof Date.now>;     // number
  8. 8

    What is structural typing?

    medium

    TypeScript compares types by their shape, not by name. An object is assignable to a type if it has all the required properties with compatible types, regardless of declared classes or interfaces. This is why two unrelated classes with the same members are interchangeable. Fresh object literals are additionally checked for excess properties.

    typescript
    interface Point { x: number; y: number }
    const p = { x: 1, y: 2, z: 3 };
    const a: Point = p;                 // ok: extra property allowed here
    // const b: Point = { x: 1, y: 2, z: 3 };   // error: excess property 'z'
  9. 9

    What is the difference between an enum, a union of literals and as const?

    medium

    A regular enum creates a runtime object, supports reverse mapping for numeric members and adds code to the bundle. A union of string literals exists only at compile time, costs nothing and is usually simpler. as const freezes an object or array literal to its narrowest literal types, so you can derive a union from its values.

    typescript
    enum Dir { Up, Down }                       // runtime object
    type Axis = "x" | "y";                      // erased at compile time
    const ROLES = ["admin", "user"] as const;
    type Role = (typeof ROLES)[number];         // "admin" | "user"
  10. 10

    What are tuples and readonly arrays?

    medium

    A tuple is an array with a fixed length and a known type at each position, such as [string, number]. Labels and optional or rest elements are supported. readonly string[] or ReadonlyArray prevents mutating methods. Tuples are how React-style hooks like useState are typed.

    typescript
    const pair: [string, number] = ["age", 30];
    const [k, v] = pair;
    // pair.push(1)  is allowed for plain tuples; use readonly to prevent
    const fixed: readonly [string, number] = ["a", 1];
    // fixed[0] = "b";   // error: read-only
  11. 11

    What are conditional types and mapped types?

    hard

    A conditional type chooses between two types based on a check, written T extends U ? X : Y, and can use infer to extract a type from inside another. A mapped type builds a new object type by iterating over the keys of another, optionally changing modifiers. Many utility types are defined with them.

    typescript
    type ElementOf<T> = T extends (infer U)[] ? U : never;
    type N = ElementOf<number[]>;               // number
    
    type Nullable<T> = { [K in keyof T]: T[K] | null };
    type P = Nullable<{ a: string }>;           // { a: string | null }
  12. 12

    What does strict mode in tsconfig turn on?

    medium

    strict is a bundle of flags: noImplicitAny, strictNullChecks, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitThis, alwaysStrict and useUnknownInCatchVariables. strictNullChecks matters most: null and undefined are no longer assignable to every type, so you must handle them explicitly with checks, optional chaining or non-null assertions.

  13. 13

    What is a type assertion, and how does it differ from a type guard?

    medium

    An assertion, value as Type, tells the compiler to trust you without any runtime check, and a wrong assertion causes runtime errors. A type guard is code that checks at runtime, such as typeof, instanceof or a function returning value is Type, and the compiler narrows based on it. Prefer guards for external data. The non-null assertion operator is a special assertion that removes null and undefined.

    typescript
    interface Cat { meow(): void }
    function isCat(x: unknown): x is Cat {
      return typeof x === "object" && x !== null && "meow" in x;
    }
    declare const pet: unknown;
    if (isCat(pet)) pet.meow();        // narrowed by a real check
    const el = document.getElementById("a") as HTMLInputElement;   // trust me
  14. 14

    How do you type functions, optional parameters and overloads?

    medium

    Annotate parameters and the return type. Optional parameters use a question mark and must follow required ones, and defaults make a parameter optional too. Overloads declare several call signatures above a single implementation, so different argument types produce different return types.

    typescript
    function greet(name: string, greeting = "Hi", punct?: string): string {
      return `${greeting} ${name}${punct ?? ""}`;
    }
    function pad(x: string): string;
    function pad(x: number): number;
    function pad(x: string | number) { return typeof x === "string" ? x.padStart(3) : x + 1; }
  15. 15

    What is the satisfies operator?

    hard

    satisfies, from TypeScript 4.9, checks that an expression matches a type without widening the expression's own type. With an annotation the variable takes the annotated type, losing specific information. With satisfies you keep the precise literal types and still get errors for typos or missing keys.

    typescript
    type Colors = Record<string, string | number[]>;
    const c = { red: "#f00", green: [0, 255, 0] } satisfies Colors;
    c.red.toUpperCase();      // ok: still known to be string
    c.green.map((x) => x);    // ok: still known to be number[]
  16. 16

    Do TypeScript types exist at runtime? How do you validate API data?

    medium

    No. Types are erased during compilation, so a response typed as User may contain anything. Validate external data at the boundary with a schema library such as Zod or with hand-written type guards, and infer the static type from the schema so the two never drift apart.

Frequently asked questions

Is TypeScript better than JavaScript?

It is not a replacement but a layer on top. For large codebases and teams, the earlier error detection and tooling usually pay for the extra syntax.

Does TypeScript run in the browser?

Not directly. It is compiled to JavaScript first by tsc or a bundler. Recent Node versions can strip types for some files, but production builds usually compile.

What is the difference between interface and abstract class?

An interface exists only at compile time and describes shape. An abstract class exists at runtime, can hold implementation and cannot be instantiated directly.

What does declaration file .d.ts mean?

It contains only type declarations for JavaScript code, so TypeScript can type-check usage of a plain JavaScript library.

Related guides

More in Programming Language Interview Questions by Language

See all in this section