Appearance
TypeScript in Depth
80. What are generics, and how do constraints work?
The short answer
Generics are type parameters: placeholders, written like <T>, that let one function, class or type work with many types while keeping the link between them. function first<T>(items: T[]): T returns the same type it was given, a string for strings and an Order for orders, instead of losing it to any. A constraint, T extends Something, limits which types are allowed, so the code inside can safely use what the constraint guarantees.
Without generics, types are lost:
ts
function firstAny(items: any[]) { return items[0] }
const o = firstAny(orders) // any: no autocomplete, no checksWith generics:
ts
function first<T>(items: T[]): T | undefined { // (1)
return items[0]
}
const order = first(orders) // Order | undefined // (2)
const sku = first(['tea', 'mug']) // string | undefined
function byId<T extends { id: string }>(items: T[], id: string): T | undefined { // (3)
return items.find((item) => item.id === id) // (4)
}
byId(orders, 'A12') // works: orders have an id
byId([1, 2, 3], '1') // error: number has no 'id'Tis a type parameter. It is filled in each time the function is called.- TypeScript infers
Tfrom the argument, so you rarely writefirst<Order>(...)yourself. - A constraint:
Tcan be any type, as long as it has anidstring. - Inside,
item.idis allowed, because the constraint guarantees it.
Generic types and classes:
ts
type ApiResponse<T> = { data: T; error: null } | { data: null; error: { code: string } }
class Repository<T extends { id: string }> {
private rows = new Map<string, T>()
save(row: T) { this.rows.set(row.id, row) }
get(id: string): T | undefined { return this.rows.get(id) }
}
const products = new Repository<Product>()Defaults and multiple parameters: type Page<T, Cursor = string>, function mapValues<K extends string, V, R>(...).
When not to use generics: if T appears only once in a signature, it links nothing, and a plain type is clearer. function log<T>(value: T): void is no better than function log(value: unknown): void.
81. What are the built-in utility types such as Partial, Pick, Omit and Record?
The short answer
Utility types are ready-made generic types that build new types from existing ones. Partial<T> makes every property optional, Required<T> makes them all required, Readonly<T> makes them read-only, Pick<T, K> keeps only some keys, Omit<T, K> removes some keys, Record<K, V> builds an object type with keys K and values V, and ReturnType, Parameters and Awaited read types out of functions and promises.
One User type, many derived types:
ts
type User = {
id: string
email: string
name: string
passwordHash: string
role: 'admin' | 'customer'
}
type UserPatch = Partial<Omit<User, 'id' | 'passwordHash'>> // (1)
type PublicUser = Omit<User, 'passwordHash'> // (2)
type UserSummary = Pick<User, 'id' | 'name'> // (3)
type UsersById = Record<string, PublicUser> // (4)
type RoleLabels = Record<User['role'], string> // (5)
const labels: RoleLabels = { admin: 'Administrator', customer: 'Customer' }- A PATCH body: any field may be sent, except the ones clients must never change.
- Safe to return from an API: the hash is removed from the type.
- A small view for lists.
- A dictionary of users by id.
- A record over a union: TypeScript forces you to provide a label for every role, so adding a new role later breaks the build until a label exists.
| Utility | Does |
|---|---|
Partial<T>, Required<T> | All optional, all required |
Readonly<T> | All read-only |
Pick<T, K>, Omit<T, K> | Keep or drop keys |
Record<K, V> | Object with keys K, values V |
Exclude<U, X>, Extract<U, X> | Remove or keep members of a union |
NonNullable<T> | Remove null and undefined |
ReturnType<F>, Parameters<F> | Read a function's return or argument types |
Awaited<T> | The value inside a promise |
Reading types out of functions keeps them in sync with the code:
ts
async function loadDashboard(userId: string) { /* returns a big object */ }
type Dashboard = Awaited<ReturnType<typeof loadDashboard>>All of these are written with mapped and conditional types (questions 83 and 84), so you can build your own.
82. What do keyof, typeof and indexed access types do?
The short answer
keyof T gives the union of a type's property names: keyof { id: string; total: number } is 'id' | 'total'. In a type position, typeof value gives the type of an existing JavaScript value, so you can derive types from constants. An indexed access type, T['key'], gives the type of one property. Together they let types follow your real data instead of being written twice.
ts
const PLANS = { // a real runtime value
basic: { priceGbp: 0, seats: 1 },
team: { priceGbp: 29, seats: 10 },
} as const
type Plans = typeof PLANS // (1)
type PlanName = keyof typeof PLANS // (2) 'basic' | 'team'
type Plan = (typeof PLANS)[PlanName] // (3) the two plan objects
type Seats = Plan['seats'] // (4) 1 | 10
function priceOf(name: PlanName) {
return PLANS[name].priceGbp
}
priceOf('team') // fine
priceOf('enterprise') // error: not a PlanNametypeofin a type position reads the type of thePLANSvalue.keyofturns its keys into a union of strings.- Indexed access with a union gives the union of those properties' types.
- Indexed access with one key gives one property's type. With
as const, the exact values are kept.
Generic property access, typed correctly:
ts
function getField<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key]
}
getField(order, 'totalPence') // number
getField(order, 'nope') // errortypeof has two meanings. In normal code, typeof x is the JavaScript operator that returns a string such as 'object' (question 39). After a colon or in a type declaration, it is the TypeScript type query.
83. What are mapped types?
The short answer
A mapped type builds a new object type by looping over the keys of another type: { [K in keyof T]: ... }. For every key K, you decide the new property type, and you can add or remove readonly and ?, or rename keys with as. Utility types such as Partial, Readonly and Record are mapped types, and you can write your own, for example to turn every field of a form into a validation error message.
ts
type MyPartial<T> = { [K in keyof T]?: T[K] } // (1)
type Mutable<T> = { -readonly [K in keyof T]: T[K] } // (2)
type SignupForm = { email: string; password: string; age: number }
type FormErrors<T> = { [K in keyof T]?: string } // (3)
const errors: FormErrors<SignupForm> = { email: 'Enter a valid email' }
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] // (4)
}
type FormGetters = Getters<SignupForm>
// { getEmail: () => string; getPassword: () => string; getAge: () => number }Partial, written by hand: same keys, each made optional with?.-readonlyremoves the read-only modifier;-?removes optional.- A practical one: each field of a form may have an error message. Adding a field to
SignupFormupdatesFormErrorsautomatically. - Key remapping with
asand a template literal type renames each key.
Why they matter: a type derived from another type stays correct when the original changes. Hand-written duplicates drift apart.
84. What are conditional types and the infer keyword?
The short answer
A conditional type picks a type based on a test, like a ternary for types: T extends string ? 'text' : 'other'. When T is a union, the test is applied to each member separately. The infer keyword, used inside the test, captures part of a type into a new name: T extends Promise<infer V> ? V : T pulls out the value type of a promise. Utility types such as ReturnType, Awaited and Exclude are built this way.
ts
type IsArray<T> = T extends unknown[] ? true : false // (1)
type A = IsArray<string[]> // true
type B = IsArray<string> // false
type Unwrap<T> = T extends Promise<infer V> ? V : T // (2)
type C = Unwrap<Promise<Order>> // Order
type D = Unwrap<number> // number
type MyReturnType<F> = F extends (...args: any[]) => infer R ? R : never // (3)
type MyExclude<U, X> = U extends X ? never : U // (4)
type Status = 'placed' | 'paid' | 'cancelled'
type ActiveStatus = MyExclude<Status, 'cancelled'> // 'placed' | 'paid'- A simple test: does
Tfitunknown[]? infer Vcaptures whatever is inside the promise.ReturnTypeby hand: match any function and capture its return type asR.- Distribution over unions: the test runs for each member, and returning
neverdrops that member.
A practical use: typed API routes.
ts
type Routes = {
'/orders': { GET: Order[]; POST: Order }
'/orders/:id': { GET: Order; DELETE: void }
}
type ResponseOf<P extends keyof Routes, M extends keyof Routes[P]> = Routes[P][M]
async function api<P extends keyof Routes, M extends keyof Routes[P] & string>(
path: P, method: M,
): Promise<ResponseOf<P, M>> {
const res = await fetch(path, { method })
return res.json()
}
const orders = await api('/orders', 'GET') // Order[]A warning for interviews: very clever conditional types make error messages hard to read and slow the compiler. Use them in shared library code, and keep application types simple.
85. What are discriminated unions, and how do you make a switch exhaustive?
The short answer
A discriminated union is a union of object types that all share one literal field, the tag, such as status: 'paid' or kind: 'card'. Checking that field narrows the value to the exact member, so each branch knows its own fields. To make a switch exhaustive, assign the value to a never variable in the default case: if someone later adds a new member and forgets to handle it, the code stops compiling.
ts
type OrderState =
| { status: 'placed'; placedAt: Date }
| { status: 'paid'; paidAt: Date; paymentId: string }
| { status: 'shipped'; trackingNumber: string }
| { status: 'refunded'; reason: string } // (1) added later
function describe(order: OrderState): string {
switch (order.status) {
case 'placed': return `placed at ${order.placedAt.toISOString()}`
case 'paid': return `paid with ${order.paymentId}` // (2)
case 'shipped': return `tracking ${order.trackingNumber}`
default: {
const unhandled: never = order // (3)
throw new Error(`unhandled status: ${JSON.stringify(unhandled)}`)
}
}
}- A new member is added to the union.
- Inside each case, only that member's fields are available:
order.paymentIdexists only for'paid'. - The exhaustiveness check. Before
'refunded'existed,orderhere wasnever, so the assignment compiled. Nowordercan be the refunded member, which is not assignable tonever, so the compiler reports:Type '{ status: "refunded"; ... }' is not assignable to type 'never'. You cannot forget the new case.
Why this is better than optional fields:
ts
// Weak: every field optional, nothing ties them together
type OrderLoose = { status: string; paidAt?: Date; paymentId?: string; trackingNumber?: string }With the loose version, a "shipped" order without a tracking number is allowed, and every reader must guess which fields go with which status. With the union, impossible states cannot be written down. This is often summed up as "make illegal states unrepresentable".
The same pattern for results:
ts
type Result<T> = { ok: true; value: T } | { ok: false; error: string }86. What does the satisfies operator do?
The short answer
value satisfies Type checks that a value matches a type without changing the value's own, more precise inferred type. A plain annotation, const x: Type = value, widens x to Type and forgets the specifics; as Type skips the check entirely. satisfies gives you both: an error if the value is wrong, and the exact literal types afterwards, which is ideal for configuration objects and lookup tables.
ts
type Route = { path: string; auth: boolean }
const routesAnnotated: Record<string, Route> = { // (1)
home: { path: '/', auth: false },
account: { path: '/account', auth: true },
}
routesAnnotated.acount // no error: any string key is allowed
const routes = { // (2)
home: { path: '/', auth: false },
account: { path: '/account', auth: true },
} satisfies Record<string, Route>
routes.acount // (3) error: property 'acount' does not exist
routes.home.path // string, checked against Route
const bad = {
home: { path: '/', auth: 'no' }, // (4) error: string is not boolean
} satisfies Record<string, Route>- An annotation widens the type to "any string key", so typos are not caught.
satisfieschecks every entry againstRoutebut keeps the exact keyshomeandaccount.- Typos are caught, because the inferred type only has those two keys.
- Wrong values are still rejected, unlike with
as.
: Type | as Type | satisfies Type | |
|---|---|---|---|
| Checks the value | Yes | No, trusts you | Yes |
| Resulting type | Type, widened | Type | The precise inferred type |
| Use for | Function parameters, public APIs | Rare, when you know better than the compiler | Config objects, lookup tables |
as const satisfies Type combines both: literal, read-only values that are also checked.
87. What are function overloads?
The short answer
Overloads let one function have several call signatures, each with its own parameter and return types, followed by a single implementation that handles all of them. Callers see only the overload signatures, so the return type can depend on the arguments, for example returning one Order when given an id and an array when given a filter. Often a union parameter or a generic is simpler; use overloads when the return type truly depends on which form was used.
ts
function findOrders(id: string): Promise<Order | null> // (1)
function findOrders(filter: { status: OrderStatus }): Promise<Order[]> // (2)
async function findOrders(arg: string | { status: OrderStatus }) { // (3)
if (typeof arg === 'string') return db.orders.findById(arg)
return db.orders.findMany({ where: { status: arg.status } })
}
const one = await findOrders('A12') // Order | null
const many = await findOrders({ status: 'paid' }) // Order[]- First signature: an id gives one order or
null. - Second signature: a filter gives an array.
- The implementation signature must accept every overload's arguments. It is not visible to callers.
Alternatives that are often clearer: two functions with clear names, findOrderById and findOrdersByStatus, which is usually the best choice in application code; or a generic with a conditional return type for library code.
88. What are declaration files (.d.ts)?
The short answer
A declaration file, ending in .d.ts, contains only types and no runtime code. It describes the shape of JavaScript that exists elsewhere, such as a library written in plain JavaScript, global variables, or files that a bundler handles, like .svg imports. The compiler reads it to type-check your use of that code. Many libraries ship their own; for others, community types come from the DefinitelyTyped project as @types/… packages.
ts
// types/env.d.ts
declare global {
namespace NodeJS {
interface ProcessEnv { // (1)
DATABASE_URL: string
STRIPE_SECRET_KEY: string
NODE_ENV: 'development' | 'production' | 'test'
}
}
}
declare module '*.svg' { // (2)
const url: string
export default url
}
declare module 'legacy-tax-lib' { // (3)
export function vatFor(countryCode: string): number
}
export {}- Augmenting a global type:
process.env.DATABASE_URLis now typed. Note it only describes the shape; the value still needs checking at start-up (question 79). - Typing non-code imports that a bundler handles.
- Typing a plain JavaScript library that ships without types.
Where .d.ts files come from:
| Source | Example |
|---|---|
| Bundled by the library | Most modern packages: "types" in their package.json |
| DefinitelyTyped | npm i -D @types/express |
Generated by tsc | declaration: true when you publish your own package |
| Written by you | Globals, legacy code, asset imports |
skipLibCheck: true tells the compiler not to type-check every .d.ts in node_modules, which speeds up builds a lot and avoids errors in third-party types you cannot fix.
89. What are decorators in TypeScript?
The short answer
A decorator is a function, applied with @name above a class, method, accessor or field, that can wrap or replace what it decorates. They are used for cross-cutting behaviour such as logging, timing, validation, caching and dependency injection. TypeScript 5 supports the standard ECMAScript decorators; the older "experimental" decorators, which frameworks like NestJS and Angular rely on, use a different signature and are enabled with experimentalDecorators.
A standard decorator that times a method:
ts
function timed<This, Args extends unknown[], R>(
method: (this: This, ...args: Args) => R,
context: ClassMethodDecoratorContext<This>, // (1)
) {
return function (this: This, ...args: Args): R { // (2)
const start = performance.now()
try {
return method.call(this, ...args)
} finally {
console.log(`${String(context.name)} took ${(performance.now() - start).toFixed(1)} ms`)
}
}
}
class ReportService {
@timed // (3)
buildMonthlyReport(month: string) { /* heavy work */ return month }
}- The context object tells the decorator what it is decorating, including its name.
- It returns a replacement method that wraps the original, the same idea as a higher-order function (question 18).
- Applying it is one line above the method.
Where you meet decorators in backend work:
| Framework | Decorators |
|---|---|
| NestJS | @Controller, @Get, @Injectable, @Body |
| TypeORM | @Entity, @Column, @ManyToOne |
| class-validator | @IsEmail(), @Min(1) |
These use the older experimental decorators, often together with emitDecoratorMetadata, which writes type information that the framework reads at runtime for dependency injection.
90. What are branded types, and when are they useful?
The short answer
A branded type adds an invisible tag to a basic type, such as a string, so that TypeScript treats values from different domains as different types even though they are the same at runtime. Because TypeScript checks shapes, a CustomerId and an OrderId that are both plain strings are interchangeable, which lets you pass the wrong ID. Branding, such as string & { readonly __brand: 'OrderId' }, makes that mix-up a compile error.
ts
type Brand<T, B extends string> = T & { readonly __brand: B } // (1)
type OrderId = Brand<string, 'OrderId'>
type CustomerId = Brand<string, 'CustomerId'>
type Pence = Brand<number, 'Pence'>
function toOrderId(raw: string): OrderId { // (2)
if (!/^ord_[a-z0-9]{12}$/.test(raw)) throw new Error('bad order id')
return raw as OrderId
}
function refund(orderId: OrderId, amount: Pence) { /* ... */ }
const customerId = 'cus_123' as CustomerId
refund(customerId, 500 as Pence) // (3) error: CustomerId is not OrderId
refund(toOrderId('ord_ab12cd34ef56'), 500 as Pence) // fine- The brand is an intersection with a fake property that never exists at runtime.
- A constructor function is the only place a raw string becomes an
OrderId, and it validates the format there. - Mixing IDs is now a compile error, as is passing pounds where pence are expected.
Where branding pays off: IDs of different entities, money in different units, sanitised versus raw HTML, and validated versus unvalidated input. Do not brand everything: it adds friction, so keep it for values where a mix-up would cause real damage.
91. What is the difference between abstract classes and interfaces?
The short answer
An interface only describes a shape, has no code, and disappears at runtime; a class can implement many interfaces. An abstract class is a real class that cannot be created directly: it can contain shared code, fields and constructors, and declares abstract methods that subclasses must implement. A class can extend only one abstract class. Use interfaces for contracts between parts of the system, and an abstract class when several implementations genuinely share code.
ts
interface PaymentProvider { // (1)
charge(pence: number, token: string): Promise<string>
}
abstract class BaseProvider implements PaymentProvider { // (2)
constructor(protected readonly apiKey: string) {}
async charge(pence: number, token: string) {
if (pence <= 0) throw new Error('amount must be positive') // (3) shared logic
return this.doCharge(pence, token)
}
protected abstract doCharge(pence: number, token: string): Promise<string> // (4)
}
class StripeProvider extends BaseProvider {
protected async doCharge(pence: number, token: string) {
return `ch_${token}_${pence}` // calls Stripe in real code
}
}
const p: PaymentProvider = new StripeProvider('sk_test') // (5)
// new BaseProvider('x') // error: cannot create an instance of an abstract class- The interface is the contract the rest of the system depends on.
- The abstract class implements it and holds what all providers share.
- Shared validation is written once.
- An abstract method: each provider must supply its own.
- Callers depend on the interface, so a new provider, or a fake one for local development, can be swapped in without touching them.
| Interface | Abstract class | |
|---|---|---|
| Contains code | No | Yes |
| Exists at runtime | No | Yes |
| A class can use | Many, with implements | One, with extends |
| Constructor and fields | No | Yes |
| Use for | Contracts | Shared base behaviour |
The modern habit: depend on interfaces, and prefer composition, passing in small collaborators, over deep inheritance trees (question 25).