TypeScript Interview Questions & Answers

TypeScript Interview Questions & Answers

Hey everyone! This is a simple, interview-ready Q&A sheet for TypeScript. Every answer is short and broken into easy points, with a tiny code snippet where it helps. Read it, then say it in your own words.

TIP: In interviews, always explain the "WHY" — TypeScript exists to
catch bugs BEFORE you run the code. Tie your answers back to that.

Part 1 — Fundamentals

1. What is TypeScript?

TypeScript is an open-source programming language developed by Microsoft. It is a superset of JavaScript, which means:

✅ Every valid JavaScript code is also valid TypeScript.
✅ TypeScript adds extra features — static typing, interfaces,
   enums, and better tooling (autocomplete, refactoring).
✅ TypeScript code is compiled (transpiled) into plain JavaScript,
   which browsers and Node.js can run.

2. Why use TypeScript over JavaScript?

✅ Catches errors early — at compile time, not at runtime.
✅ Great autocomplete and safer refactoring in your editor.
✅ Types act as living documentation for your code.
✅ On big projects and teams, it prevents a whole class of bugs.

3. What's the difference between TypeScript and JavaScript?

   JavaScript                    TypeScript
   ──────────                    ──────────
   Dynamically typed             Statically typed
   Types checked at runtime      Types checked at compile time
   Runs directly in browser      Must be compiled to JS first
   No interfaces / enums         Has interfaces, enums, generics

4. What happens to types when TypeScript compiles?

✅ Types are ERASED. They exist only at compile time for checking.
✅ The output is plain JavaScript with NO type information.
✅ This is called "type erasure".
✅ That's why you can't check a type at runtime like you check a value.

5. What is type inference?

TypeScript can figure out a type automatically, so you don't have to write it.

let count = 5;        // inferred as number
let name = "Aditya";  // inferred as string
// count = "hi";      // ❌ error — a number can't become a string

You only add explicit types when inference isn't enough — like on function parameters.


Part 2 — Basic Types

6. What are the basic types in TypeScript?

✅ Primitives → string, number, boolean, null, undefined, symbol, bigint
✅ Special    → any, unknown, void, never
✅ Others     → array, tuple, enum, object
✅ Plus       → union types and literal types

7. What is the difference between any, unknown, never, and void?

   any     → turns OFF type checking. Can be anything. Avoid it.
   unknown → "some value, but I don't know the type yet".
             Safe version of any — you MUST check it before using it.
   void    → a function returns NOTHING (no return value).
   never   → a value that NEVER happens (a function that always throws,
             or an infinite loop; also the "impossible" type).
✅ any     → disables safety.
✅ unknown → keeps safety, forces you to check the type first.
✅ void    → for functions with no return.
✅ never   → for code that can never finish.

8. Why is unknown safer than any?

✅ any    → TypeScript lets you do anything, so bugs slip through.
✅ unknown → you must NARROW the type (check it) before using it,
            so the compiler still protects you.
let a: any = "hello";
a.foo.bar;              // ✅ compiles, 💥 crashes at runtime

let u: unknown = "hello";
// u.toUpperCase();     // ❌ error — must check first
if (typeof u === "string") u.toUpperCase();  // ✅ safe

9. What is a union type?

A type that can be one of several types, written with a pipe |.

let id: string | number;   // can be a string OR a number

You usually narrow it with a type check before using it.

10. What is an intersection type?

A type that combines multiple types into one, written with &. The value must have ALL the properties.

type A = { name: string };
type B = { age: number };
type Person = A & B;    // must have BOTH name and age
✅ Union (|)        → either / or
✅ Intersection (&) → both / and

11. What are literal types?

Types that are an exact value, not just a general type.

let dir: "left" | "right";
dir = "left";    // ✅ ok
// dir = "up";   // ❌ error — only "left" or "right" allowed

Great for restricting a value to a fixed set of options.


Part 3 — Interfaces & Types

12. What is an interface?

An interface describes the shape of an object — what properties and methods it has, and their types. Think of it as a contract.

interface User {
    id: number;
    name: string;
    isAdmin?: boolean;   // optional
}

13. What's the difference between interface and type?

   interface                     type
   ─────────                     ────
   Can be re-opened / merged     Cannot be re-declared
   (declaration merging)
   Only for object shapes        Can be ANYTHING: unions,
                                 primitives, tuples, etc.
   Uses "extends"                Uses "&" to combine
✅ Rule of thumb:
   • Use interface → for object shapes and public APIs.
   • Use type      → for unions, intersections, or aliases.
   • For most objects, they work the same way.

14. What are optional and readonly properties?

interface User {
    id: number;
    readonly email: string;   // can't be changed after creation
    nickname?: string;        // optional — may be missing
}
✅ ?         → makes a property optional.
✅ readonly  → can be set once, but not changed later.

15. What is an index signature?

It lets an object have any number of keys of a certain type, when you don't know the key names in advance.

interface Scores {
    [studentName: string]: number;   // any string key → number value
}
const s: Scores = { aditya: 90, riya: 85 };

Part 4 — Functions

16. How do you type a function?

function add(a: number, b: number): number {
    return a + b;
}
// a, b  → parameter types
// : number (at the end) → return type

17. How do optional and default parameters work?

function greet(name: string, greeting?: string) { }        // optional
function greet2(name: string, greeting = "Hello") { }      // default
✅ ?          → parameter is optional (may be undefined).
✅ = "Hello"  → default value used when nothing is passed.
✅ Optional params must come AFTER required ones.

18. What is function overloading?

It lets one function have multiple type signatures for different arguments. You write the overload signatures, then one implementation.

function len(x: string): number;
function len(x: any[]): number;
function len(x: string | any[]): number {
    return x.length;
}

Part 5 — Generics

19. What are generics?

Generics let you write reusable code that works with any type — while staying type-safe. You use a type variable (often T) that gets filled in when the function is called.

function identity<T>(value: T): T {
    return value;
}
identity<string>("hi");   // T is string
identity(42);            // T inferred as number

20. Why use generics instead of any?

✅ any      → throws away type info. You lose safety and autocomplete.
✅ generics → keep the link between input and output types.
             Pass a string → get a string back. Safe AND reusable.

21. What is a generic constraint?

It restricts what types a generic can accept, using extends.

function longest<T extends { length: number }>(a: T, b: T): T {
    return a.length >= b.length ? a : b;
}
longest("abc", "de");    // ✅ strings have length
// longest(1, 2);        // ❌ numbers have no length

Part 6 — Type Narrowing & Guards

22. What is type narrowing?

It's when TypeScript figures out a more specific type inside a block, based on your checks.

function print(x: string | number) {
    if (typeof x === "string") {
        // TS knows x is a string here
        x.toUpperCase();
    }
}

23. What are type guards?

Checks that narrow a type. They tell the compiler which type you have in a branch.

✅ typeof        → for primitives (string, number...)
✅ instanceof    → for classes
✅ in            → checks if a property exists
✅ custom guard  → a function returning "x is Type"
function isString(x: unknown): x is string {
    return typeof x === "string";
}

24. What is a discriminated union?

A union of objects that share a common literal property (the "discriminant"), which lets you narrow safely.

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

function area(s: Shape) {
    if (s.kind === "circle") return Math.PI * s.radius ** 2;
    return s.side ** 2;   // TS knows it's a square here
}

Part 7 — Advanced Types

25. What are keyof and typeof?

✅ keyof  → gives a union of an object type's KEYS
✅ typeof → gives the TYPE of a value (in a type context)
interface User { id: number; name: string; }
type UserKeys = keyof User;      // "id" | "name"

const config = { port: 3000 };
type Config = typeof config;     // { port: number }

26. What are utility types? Name a few.

Built-in generic helpers that transform types. Common ones:

UtilityWhat it does
Partial<T>Makes all properties optional
Required<T>Makes all properties required
Readonly<T>Makes all properties readonly
Pick<T, K>Keep only certain keys
Omit<T, K>Remove certain keys
Record<K, V>Object with keys K and values V
Exclude / ExtractFilter members out of / into a union
ReturnType<T>The return type of a function
interface User { id: number; name: string; email: string; }

type PartialUser = Partial<User>;          // all optional
type NameOnly    = Pick<User, "name">;      // { name: string }
type NoEmail     = Omit<User, "email">;     // id + name

27. What are mapped types?

They create a new type by looping over each property of an existing type. This is how Partial and Readonly are built inside.

type MyReadonly<T> = {
    readonly [K in keyof T]: T[K];
};

28. What are conditional types?

Types that choose between two types based on a condition — like a ternary, but with extends.

type IsString<T> = T extends string ? "yes" : "no";
type A = IsString<string>;   // "yes"
type B = IsString<number>;   // "no"

29. What does as const do?

✅ Makes a value deeply readonly.
✅ Infers the narrowest literal types (not the general type).
✅ An array becomes a readonly tuple.
const dirs = ["left", "right"] as const;
// type: readonly ["left", "right"]  (not string[])

30. What is a type assertion?

It tells the compiler to treat a value as a specific type, using as, when you know more than it does.

const el = document.getElementById("app") as HTMLInputElement;

⚠️ It doesn't change the value at runtime — it only overrides the compiler. Use it carefully.


Part 8 — Enums, Tuples & Classes

31. What is an enum?

A way to give friendly names to a set of related constant values.

enum Direction { Up, Down, Left, Right }   // 0, 1, 2, 3
enum Status { Active = "ACTIVE", Done = "DONE" }
✅ Numeric enums → auto-increment (0, 1, 2...)
✅ String enums  → hold explicit strings
✅ Note: many teams now prefer union literals or "as const"
   objects, since enums add extra runtime code.

32. What is a tuple?

A fixed-length array where each position has a known type.

let point: [number, number] = [10, 20];
let entry: [string, number] = ["age", 30];

Useful for pairs — like a coordinate, or a React useState return.

33. What are access modifiers in classes?

   public    → accessible anywhere (default)
   private   → only inside the same class
   protected → inside the class and its subclasses
   readonly  → can't be reassigned after initialization
class Account {
    private balance = 0;
    readonly id: string;
    constructor(id: string) { this.id = id; }
}

34. What is an abstract class?

✅ A base class that CAN'T be created directly (no "new").
✅ Meant to be extended by other classes.
✅ Can have abstract methods that subclasses MUST implement.
✅ Can also hold shared, ready-made logic.

35. Can a class implement an interface?

✅ Yes → class Dog implements Animal
✅ The class must provide everything the interface declares.
✅ A class can implement MULTIPLE interfaces at once.

Part 9 — Config & Concepts

36. What is structural typing (duck typing)?

TypeScript checks types by their shape, not their name.

✅ If two types have the same structure, they're compatible.
✅ "If it walks like a duck and quacks like a duck, it's a duck."
✅ An object fits a type if it has all the required properties —
   no matter how it was declared.

37. What is tsconfig.json?

The configuration file for the TypeScript compiler. It controls:

✅ target      → which JavaScript version to output
✅ module      → which module system to use
✅ include     → which files to compile
✅ strict      → strictness / safety options

38. What does strict mode do?

✅ Turns on a group of strict checks at once
   (like strictNullChecks and noImplicitAny).
✅ Catches more bugs.
✅ Strongly recommended — especially strictNullChecks.

39. What is strictNullChecks?

✅ null and undefined are NOT part of every type automatically.
✅ You must handle them explicitly.
✅ This prevents the classic
   "cannot read property of undefined" crash.

40. What are declaration files (.d.ts)?

✅ Files that describe types of existing JS code — no implementation.
✅ They let TypeScript understand plain JavaScript libraries.
✅ Many packages ship their own.
✅ Community types live in DefinitelyTyped, under @types.

41. What are decorators?

✅ Special functions prefixed with @
✅ Add behavior or metadata to classes, methods, or properties.
✅ Heavily used in Angular and NestJS.
✅ Opt-in feature — enabled in tsconfig.

42. What's the difference between null and undefined?

✅ undefined → declared but never assigned a value.
✅ null      → an explicit "no value".
✅ With strictNullChecks on, both must be handled in the types.
✅ Use optional chaining (?.) and nullish coalescing (??)
   to deal with them safely.

Final Interview Tips

┌─────────────────────────────────────────────────────────────┐
│            TYPESCRIPT INTERVIEW CHECKLIST                   │
├─────────────────────────────────────────────────────────────┤
│  ✔ Always explain WHY: catch bugs at compile time           │
│  ✔ Know any vs unknown vs never cold — very common Q         │
│  ✔ interface vs type — expect it in every interview          │
│  ✔ Be ready to write a generic function on the spot          │
│  ✔ Know 4-5 utility types (Partial, Pick, Omit, Record...)   │
│  ✔ Mention strictNullChecks when talking about safety        │
│  ✔ Prefer unknown over any, and say so — shows good taste    │
└─────────────────────────────────────────────────────────────┘

All the best — you've got this! 🚀