Skip to content

Interview PrepTypeScript · Core

TypeScript Basics ​

70. What is TypeScript, and why use it? ​

The short answer

TypeScript is JavaScript with a type system added on top. You describe the shapes of your data, the compiler checks your code against those descriptions before it runs, and then the types are removed, leaving plain JavaScript. It catches whole classes of bugs early, such as calling a function with the wrong arguments or reading a property that might be missing, and it makes large codebases safer to change, because the editor knows what every value is.

The bug it prevents:

ts
type Order = { id: string; totalPence: number; customerEmail?: string }

function sendReceipt(order: Order) {
  return email(order.customerEmail.toLowerCase(), `Total £${order.totalPence / 100}`)
  //                           ~~~~~~~~~~~~~ error: 'order.customerEmail' is possibly 'undefined'
}

sendReceipt({ id: 'A12', total: 1999 })
//                       ~~~~~ error: 'total' does not exist in type 'Order'

In plain JavaScript, both mistakes only show up when a customer hits them in production. TypeScript reports them while you type.

What you get, beyond bug catching:

BenefitWhy it matters
Autocomplete and inline docsThe editor knows every field and method
Safe refactoringRename a field and every use updates, or errors
Code as documentationA function's type says what it takes and returns
Contracts between teamsShared types for API requests and responses

What it costs: a build or type-check step, learning the type system, and sometimes fighting complex types from libraries.

How it runs. Browsers and Node.js run JavaScript. TypeScript is turned into JavaScript in one of two ways:

  1. Type-check and compile with tsc, the official compiler.
  2. Strip the types with a fast tool, such as esbuild, which Vite uses, or Node.js itself, which can now run .ts files directly by removing the type syntax. Type-stripping does no checking, so tsc --noEmit still runs in the editor and in CI.

Current state, late 2026. TypeScript 6.0, released in March 2026, was the last version of the compiler written in JavaScript and made strict the default. TypeScript 7 is the compiler rewritten in Go, about ten times faster, and reached release candidate in mid-2026.

71. What is the difference between type and interface? ​

The short answer

Both describe the shape of an object and, for most object types, are interchangeable. interface can only describe object shapes, can be extended with extends, and can be re-opened: two declarations with the same name merge. type is an alias for any type at all, including unions, tuples, primitives and computed types, but cannot be re-opened. A common team rule: use interface for public object shapes that others may extend, and type for everything else, especially unions.

ts
interface Customer {                     // (1)
  id: string
  email: string
}
interface Customer {                     // (2) merges with the one above
  loyaltyPoints: number
}
interface VipCustomer extends Customer { // (3)
  accountManager: string
}

type OrderStatus = 'placed' | 'paid' | 'shipped'          // (4)
type Money = { pence: number; currency: 'GBP' | 'EUR' }
type PricedLine = { sku: string } & Money                 // (5)
type Coordinates = [lat: number, lng: number]             // (6)
  1. An interface describing an object.
  2. Declaration merging: a second interface with the same name adds fields. Libraries use this so you can add fields to, say, Express's Request type.
  3. extends builds a bigger interface from a smaller one.
  4. A union of string literals: only type can do this.
  5. An intersection combining two types (question 73).
  6. A tuple: also only type.
interfacetype
Object shapesYesYes
Unions, tuples, primitives, mapped typesNoYes
Extendextends& intersection
Declaration mergingYesNo: a duplicate name is an error
Error messagesShows the interface nameSometimes expands the whole type
Implementing in a classimplementsimplements works for object types too

Augmenting a library type, the main reason merging exists:

ts
// types/express.d.ts
declare global {
  namespace Express {
    interface Request { user?: { id: string; role: 'admin' | 'customer' } }
  }
}
export {}

Now req.user is typed in every Express handler.

72. What is the difference between any, unknown, and never? ​

The short answer

any switches type checking off: anything can be assigned to it and you can do anything with it, so errors slip through. unknown also accepts any value, but you must check what it is before using it, so it is the safe type for data you have not validated, such as JSON.parse output or a caught error. never is the type with no values at all: it marks code that cannot be reached, functions that never return, and impossible cases in exhaustive checks.

ts
const a: any = JSON.parse('{"total": 40}')
a.totl.toFixed(2)                 // (1) compiles; crashes at runtime

const u: unknown = JSON.parse('{"total": 40}')
u.total                           // (2) error: 'u' is of type 'unknown'
if (typeof u === 'object' && u !== null && 'total' in u && typeof u.total === 'number') {
  u.total.toFixed(2)              // (3) fine: narrowed
}

function fail(message: string): never {   // (4)
  throw new Error(message)
}
  1. any lets a typo through: no error until it runs.
  2. unknown blocks use until you prove what it is.
  3. After checks, TypeScript knows the shape (question 74). In practice, a schema library does this checking for you (question 79).
  4. never as a return type: this function always throws, so it never returns a value.
anyunknownnever
Accepts any valueYesYesNo value at all
Can be used without checksYesNoNot applicable
Assignable to other typesYes, to anythingOnly to unknown and anyYes, to anything
Use it forEscape hatch, migrationUntrusted input, caught errorsImpossible cases, exhaustive checks

Caught errors are unknown in strict mode, because anything can be thrown in JavaScript:

ts
try {
  await charge(token, 1999)
} catch (err) {
  const message = err instanceof Error ? err.message : String(err)
  logger.error({ message }, 'charge failed')
}

never in exhaustive checks makes the compiler tell you when a new case is added but not handled (question 85).

Rule of thumb: treat any as a code smell. Turn on the noImplicitAny check, which strict includes (question 78), and reach for unknown instead.

73. What are union and intersection types? ​

The short answer

A union type, A | B, is a value that can be one of several types: string | number is a string or a number. An intersection type, A & B, is a value that has all the properties of both types at once. Unions are used for "one of these" cases, such as statuses or results that succeed or fail, and you narrow them before use. Intersections are used to combine object types, such as adding audit fields to an entity.

ts
type PaymentMethod = 'card' | 'paypal' | 'bank-transfer'      // (1)
type OrderId = string | number                                 // (2)

type Timestamps = { createdAt: Date; updatedAt: Date }
type Product = { sku: string; name: string; pricePence: number }
type StoredProduct = Product & Timestamps                      // (3)

function formatId(id: OrderId) {
  return typeof id === 'number' ? `#${id}` : id.toUpperCase()  // (4)
}
  1. A union of literal types: only these three strings are allowed.
  2. A union of primitives.
  3. An intersection: a StoredProduct has every field of both types.
  4. Using a union: you must narrow it first, because only methods common to both members are allowed until you check (question 74).

The naming trick that confuses people. A union of object types allows fewer properties to be used directly, only the shared ones, while an intersection has more properties. The names describe the sets of values: a union value comes from either set, an intersection value is in both sets at once.

An impossible intersection becomes never: string & number has no values.

74. What is type narrowing, and what are type guards? ​

The short answer

Narrowing is TypeScript working out a more specific type inside a block of code after a check, such as knowing a value is a string inside if (typeof x === 'string'). The checks that narrow are called type guards: typeof, instanceof, in, equality checks, truthiness checks, and checks on a shared tag field in discriminated unions. You can also write your own guard function whose return type is value is SomeType.

ts
type CardPayment = { kind: 'card'; last4: string }
type PaypalPayment = { kind: 'paypal'; email: string }
type Payment = CardPayment | PaypalPayment

function describe(p: Payment | null, note: string | number) {
  if (p === null) return 'no payment'                    // (1) equality
  if (typeof note === 'number') note = String(note)      // (2) typeof

  if (p.kind === 'card') {                               // (3) tag check
    return `card ending ${p.last4}`
  }
  return `PayPal ${p.email}`                             // (4) only PayPal left
}

class PaymentError extends Error { code = 'PAYMENT' }
function isPaymentError(e: unknown): e is PaymentError {   // (5)
  return e instanceof PaymentError
}
  1. After p === null returns, TypeScript knows p is a Payment below.
  2. typeof narrows primitives.
  3. Checking the shared kind field narrows to CardPayment. This is a discriminated union (question 85).
  4. The only remaining member is PaypalPayment, so p.email is allowed.
  5. A custom type guard: when it returns true, the compiler treats e as a PaymentError in that branch.

The guards you will use:

GuardNarrowsExample
typeof x === 'string'PrimitivesStrings, numbers, booleans
x instanceof DateClassesDates, errors, your classes
'email' in xObjects by propertyShapes without a tag
x.kind === 'card'Discriminated unionsTagged object types
x != null, if (x)Removes null and undefinedOptional values
function isX(v): v is XAnythingYour own checks
asserts v is XThe rest of the functionassertIsOrder(v)

A custom guard is a promise to the compiler. If its body is wrong, TypeScript believes it anyway. Keep guards small and obvious.

75. What is structural typing? ​

The short answer

TypeScript checks types by their shape, not by their name: if a value has all the properties a type requires, with compatible types, it fits that type, even if it was never declared as that type. This is called structural typing, sometimes "duck typing at compile time". It differs from nominal typing in Java or C#, where a class must explicitly declare that it implements an interface.

ts
interface HasEmail { email: string }

class Customer { constructor(public id: string, public email: string) {} }
const supplier = { name: 'Acme', email: 'orders@acme.example' }

function notify(target: HasEmail) { /* ... */ }

notify(new Customer('c1', 'p@shop.example'))   // (1) fine
notify(supplier)                               // (2) fine
  1. Customer never mentions HasEmail, but it has an email string, so it fits.
  2. A plain object with an email also fits. The extra name is allowed.

The exception: excess property checks. An object literal written directly in the call is checked strictly, to catch typos:

ts
notify({ email: 'a@b.example', emial: 'typo' })
//                              ~~~~~ error: object literal may only specify known properties

When structural typing is not what you want. A CustomerId and an OrderId that are both string are interchangeable, so passing one where the other is expected compiles fine. Branded types fix that when it matters (question 90).

76. What are enums, and why do many teams prefer union types? ​

The short answer

An enum is a TypeScript feature that defines a named set of constants, such as enum Status { Placed, Paid }. Unlike most TypeScript features, it generates real JavaScript code at runtime, numeric enums allow any number to be assigned, and they do not work with tools that only strip types. Many teams prefer a union of string literals, type Status = 'placed' | 'paid', or a const object with as const, which are simpler, produce no surprises, and erase cleanly.

ts
enum OrderStatus { Placed, Paid, Shipped }             // (1) numeric: 0, 1, 2
const s: OrderStatus = 42                              // (2) allowed in older TS versions

type Status = 'placed' | 'paid' | 'shipped'            // (3)

const ORDER_STATUS = {                                 // (4)
  Placed: 'placed',
  Paid: 'paid',
  Shipped: 'shipped',
} as const
type OrderStatus2 = (typeof ORDER_STATUS)[keyof typeof ORDER_STATUS]   // 'placed' | 'paid' | 'shipped'
  1. A numeric enum. It compiles to a JavaScript object with two-way mappings.
  2. Loose numeric assignment was historically allowed, which defeats the point. Newer versions are stricter, but the habit stuck.
  3. A union of string literals: zero runtime code, readable values in logs and the database.
  4. A const object when you also want a runtime list of values, for dropdowns or validation, plus a derived union type.
enumString literal unionas const object
Runtime codeYesNoneThe object only
Values in logs and JSONNumbers, unless string enumReadable stringsReadable strings
Works with type-stripping toolsNo, by defaultYesYes
List all values at runtimeYesNoYes: Object.values

Why "type-stripping" matters now: Node.js's built-in TypeScript support and tools like it only remove type annotations. An enum needs code generated, so it fails unless a transform is turned on, and the erasableSyntaxOnly option exists to forbid enums and similar features for that reason.

77. What do optional, readonly and tuple types do? ​

The short answer

An optional property, discount?: number, may be missing, so its type includes undefined and you must check it before use. readonly stops a property, or a whole array, from being reassigned through that type, which documents and enforces "do not change this". A tuple, [number, number], is an array of a fixed length where each position has its own type, useful for pairs such as coordinates or a [value, setter] return.

ts
type Order = {
  readonly id: string                 // (1)
  items: readonly string[]            // (2)
  giftMessage?: string                // (3)
}

function update(order: Order) {
  order.id = 'B2'                     // error: cannot assign to 'id'
  order.items.push('mug')             // error: 'push' does not exist on readonly string[]
  order.giftMessage?.trim()           // must handle the missing case
}

type LatLng = [lat: number, lng: number]                   // (4)
function useCounter(): [count: number, increment: () => void] {   // (5)
  let count = 0
  return [count, () => { count += 1 }]
}
const [count, increment] = useCounter()
  1. readonly property: assignment is a compile error.
  2. Readonly array: no push, pop or sort through this type. ReadonlyArray<T> is the same.
  3. Optional: the type is string | undefined.
  4. A labelled tuple: two numbers, in that order. The labels only help readability.
  5. Returning a tuple, the pattern React's useState uses, so callers can name the parts when destructuring.

readonly is compile-time only. At runtime, the object can still be changed by code that does not go through this type. For a runtime guarantee, use Object.freeze (question 27).

Optional versus | undefined. discount?: number means the key may be absent. discount: number | undefined means the key must be present, but its value may be undefined. With the exactOptionalPropertyTypes option, TypeScript keeps those two apart, which matters for PATCH requests (question 34).

78. What does strict mode in tsconfig turn on? ​

The short answer

"strict": true turns on a family of checks that make TypeScript catch far more bugs. The most important are strictNullChecks, so null and undefined must be handled explicitly, and noImplicitAny, so untyped values are errors instead of silent any. It also adds strict function types, strict property initialisation in classes, unknown for caught errors and this checks. Since TypeScript 6.0 it is the default, and every new project should keep it on.

CheckCatches
strictNullChecksUsing a value that may be null or undefined
noImplicitAnyParameters and variables that would silently be any
strictFunctionTypesUnsafe function parameter types in callbacks
strictPropertyInitializationClass fields never assigned in the constructor
strictBindCallApplyWrong arguments to call, apply and bind
useUnknownInCatchVariablesCaught errors typed as unknown, not any
noImplicitThisthis with an unknown type
alwaysStrictEmits 'use strict', JavaScript strict mode

Useful checks outside strict:

OptionCatches
noUncheckedIndexedAccessitems[5] might be undefined
exactOptionalPropertyTypesMixing "missing" with "present but undefined"
noImplicitOverrideOverriding a parent method without saying override
noFallthroughCasesInSwitchForgetting break in a switch

The one that finds the most real bugs is strictNullChecks. Without it, string silently includes null, and "cannot read properties of null" errors come back.

Turning strict on in an old codebase: switch it on and fix errors file by file, or enable the checks one at a time, starting with noImplicitAny. Mark temporary exceptions with // @ts-expect-error, which fails once the error is fixed, rather than // @ts-ignore.

79. Does TypeScript check anything at runtime? ​

The short answer

No. TypeScript types exist only at compile time and are completely removed in the JavaScript that runs. If a request body, a database row or an API response does not match your type, nothing stops it at runtime; the code just assumes it does. So data crossing a trust boundary must be validated at runtime with a schema library, such as Zod, Valibot or a JSON Schema validator, which checks the real value and also gives you the TypeScript type.

The false sense of safety:

ts
type CreateOrder = { sku: string; qty: number }

app.post('/orders', (req, res) => {
  const body = req.body as CreateOrder         // (1) a promise to the compiler, not a check
  const total = body.qty * 4.5                 // (2) qty may be "5" or missing
})
  1. as only tells the compiler what to believe. It checks nothing.
  2. The client can send anything. qty could be a string, negative, or absent.

Validating for real, with Zod:

ts
import { z } from 'zod'

const CreateOrderSchema = z.object({                     // (1)
  sku: z.string().min(1),
  qty: z.number().int().positive().max(100),
})
type CreateOrder = z.infer<typeof CreateOrderSchema>     // (2)

app.post('/orders', (req, res) => {
  const result = CreateOrderSchema.safeParse(req.body)   // (3)
  if (!result.success) {
    return res.status(400).json({ error: 'invalid_body', issues: result.error.issues })
  }
  const order: CreateOrder = result.data                 // (4) checked and typed
})
  1. A schema describes the rules, and it exists at runtime.
  2. The TypeScript type is derived from the schema, so the two can never drift apart.
  3. safeParse checks the real value and returns success or a list of problems.
  4. Inside the success branch, the data is both validated and correctly typed.

Where to validate: at every boundary where outside data enters: request bodies and query strings, environment variables at start-up, responses from other services, messages from queues, and files. Inside your program, trust the types.

as, ! and any are the three ways to tell TypeScript to stop checking. Each one is a place where a runtime error can hide, so keep them rare and justified.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
JavaScript & TypeScript
Basics
Async
TypeScript
Write it yourself
Other topics
Nothing picked yet