Appearance
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:
| Benefit | Why it matters |
|---|---|
| Autocomplete and inline docs | The editor knows every field and method |
| Safe refactoring | Rename a field and every use updates, or errors |
| Code as documentation | A function's type says what it takes and returns |
| Contracts between teams | Shared 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:
- Type-check and compile with
tsc, the official compiler. - Strip the types with a fast tool, such as esbuild, which Vite uses, or Node.js itself, which can now run
.tsfiles directly by removing the type syntax. Type-stripping does no checking, sotsc --noEmitstill 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)- An interface describing an object.
- Declaration merging: a second interface with the same name adds fields. Libraries use this so you can add fields to, say, Express's
Requesttype. extendsbuilds a bigger interface from a smaller one.- A union of string literals: only
typecan do this. - An intersection combining two types (question 73).
- A tuple: also only
type.
interface | type | |
|---|---|---|
| Object shapes | Yes | Yes |
| Unions, tuples, primitives, mapped types | No | Yes |
| Extend | extends | & intersection |
| Declaration merging | Yes | No: a duplicate name is an error |
| Error messages | Shows the interface name | Sometimes expands the whole type |
| Implementing in a class | implements | implements 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)
}anylets a typo through: no error until it runs.unknownblocks use until you prove what it is.- After checks, TypeScript knows the shape (question 74). In practice, a schema library does this checking for you (question 79).
neveras a return type: this function always throws, so it never returns a value.
any | unknown | never | |
|---|---|---|---|
| Accepts any value | Yes | Yes | No value at all |
| Can be used without checks | Yes | No | Not applicable |
| Assignable to other types | Yes, to anything | Only to unknown and any | Yes, to anything |
| Use it for | Escape hatch, migration | Untrusted input, caught errors | Impossible 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)
}- A union of literal types: only these three strings are allowed.
- A union of primitives.
- An intersection: a
StoredProducthas every field of both types. - 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
}- After
p === nullreturns, TypeScript knowspis aPaymentbelow. typeofnarrows primitives.- Checking the shared
kindfield narrows toCardPayment. This is a discriminated union (question 85). - The only remaining member is
PaypalPayment, sop.emailis allowed. - A custom type guard: when it returns
true, the compiler treatseas aPaymentErrorin that branch.
The guards you will use:
| Guard | Narrows | Example |
|---|---|---|
typeof x === 'string' | Primitives | Strings, numbers, booleans |
x instanceof Date | Classes | Dates, errors, your classes |
'email' in x | Objects by property | Shapes without a tag |
x.kind === 'card' | Discriminated unions | Tagged object types |
x != null, if (x) | Removes null and undefined | Optional values |
function isX(v): v is X | Anything | Your own checks |
asserts v is X | The rest of the function | assertIsOrder(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) fineCustomernever mentionsHasEmail, but it has anemailstring, so it fits.- A plain object with an
emailalso fits. The extranameis 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 propertiesWhen 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'- A numeric enum. It compiles to a JavaScript object with two-way mappings.
- Loose numeric assignment was historically allowed, which defeats the point. Newer versions are stricter, but the habit stuck.
- A union of string literals: zero runtime code, readable values in logs and the database.
- A
constobject when you also want a runtime list of values, for dropdowns or validation, plus a derived union type.
enum | String literal union | as const object | |
|---|---|---|---|
| Runtime code | Yes | None | The object only |
| Values in logs and JSON | Numbers, unless string enum | Readable strings | Readable strings |
| Works with type-stripping tools | No, by default | Yes | Yes |
| List all values at runtime | Yes | No | Yes: 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()readonlyproperty: assignment is a compile error.- Readonly array: no
push,poporsortthrough this type.ReadonlyArray<T>is the same. - Optional: the type is
string | undefined. - A labelled tuple: two numbers, in that order. The labels only help readability.
- Returning a tuple, the pattern React's
useStateuses, 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.
| Check | Catches |
|---|---|
strictNullChecks | Using a value that may be null or undefined |
noImplicitAny | Parameters and variables that would silently be any |
strictFunctionTypes | Unsafe function parameter types in callbacks |
strictPropertyInitialization | Class fields never assigned in the constructor |
strictBindCallApply | Wrong arguments to call, apply and bind |
useUnknownInCatchVariables | Caught errors typed as unknown, not any |
noImplicitThis | this with an unknown type |
alwaysStrict | Emits 'use strict', JavaScript strict mode |
Useful checks outside strict:
| Option | Catches |
|---|---|
noUncheckedIndexedAccess | items[5] might be undefined |
exactOptionalPropertyTypes | Mixing "missing" with "present but undefined" |
noImplicitOverride | Overriding a parent method without saying override |
noFallthroughCasesInSwitch | Forgetting 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
})asonly tells the compiler what to believe. It checks nothing.- The client can send anything.
qtycould 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
})- A schema describes the rules, and it exists at runtime.
- The TypeScript type is derived from the schema, so the two can never drift apart.
safeParsechecks the real value and returns success or a list of problems.- 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.