devsetswww.devsets.com/en/topics/typescript/notes
TypeScript quick reference for interviews
The essentials of the topic on a couple of pages: key concepts by section and the pitfalls interviewers like to ask about.
Basic types
- Primitives.
string,number,boolean,bigint,symbol,null,undefined. Write them in lowercase:StringandNumberare wrapper objects.- any and unknown.
anyturns off checking and spreads to everything it touches.unknownaccepts any value but must be narrowed before use, so it's the safe choice for external data.- never.
- A type with no values: a function that always throws, an impossible branch, an empty union. Useful for exhaustive checks.
- void.
- The return type of a function whose result isn't used. A callback typed
() => voidmay still return a value, it's just ignored. - Literal types.
"get" | "post",0 | 1.constinfers a literal,letwidens it tostringornumber.- Arrays and tuples.
string[]orArray<string>. A tuple has a fixed length and types by position:[string, number], with optional names[id: string, age: number].- as const.
- Makes a literal deeply
readonlyand keeps exact values:["a", "b"] as consthas the typereadonly ["a", "b"].
Object types
- interface and type.
- Both describe object shapes. Interfaces with the same name merge and are extended with
extends. Atypealias can also be a union, tuple, mapped or conditional type. - Optional and readonly.
name?: stringmay be missing,readonly id: stringcan't be reassigned.readonlyis checked only at compile time.- Index signature.
{ [key: string]: number }for objects with arbitrary keys.Record<string, number>is the same thing written shorter.- Structural typing.
- Types are compatible by shape, not by name: any object with the right properties fits. For nominal types, add a brand:
string & { __brand: "UserId" }. - Excess property check.
- An object literal passed directly is checked for unknown properties. The same object from a variable passes if it has the required ones.
- Intersection.
A & Bhas the properties of both. Conflicting property types becomenever.
Unions and narrowing
- Union.
string | number: only members common to all variants are available until the type is narrowed.- Narrowing.
typeof x === "string",x instanceof Date,"id" in x,Array.isArray(x), a check fornullor truthiness. Inside the branch, TypeScript knows the narrower type.- Discriminated union.
- Each variant has a common literal field like
kindortype. Aswitchon it narrows to one variant. - Exhaustive check.
- In
default, assign the value tonever: when a new variant is added, the code stops compiling. - Type predicate.
function isUser(x: unknown): x is Usertells the compiler what atrueresult means. Since TypeScript 5.5, simple predicates likex => x !== undefinedinfilterare inferred.- Assertion function.
function assert(v: unknown): asserts v is stringthrows on bad input, and after the call the type is narrowed.
type Shape =
| { kind: "circle"; r: number }
| { kind: "square"; side: number };
function area(s: Shape): number {
switch (s.kind) {
case "circle":
return Math.PI * s.r ** 2;
case "square":
return s.side ** 2;
default: {
const unreachable: never = s;
return unreachable;
}
}
}Functions
- Signatures.
- Parameter types are required, the return type is usually inferred. Write it explicitly for public APIs and recursive functions.
- Optional and default.
(name?: string)isstring | undefined. A default value(n = 10)makes the parameter optional and infers its type.- Overloads.
- Several signatures above one implementation. Callers see only the overloads, not the implementation signature.
- this parameter.
function (this: HTMLElement)typesthis. It's a fake first parameter and is removed from the output.- Contextual typing.
- A callback passed to
mapor an event listener gets its parameter types from the context, without annotations.
Generics
- Generic.
- A type parameter keeps the link between input and output:
function first<T>(a: T[]): T | undefined. Usually inferred from arguments. - Constraint.
<T extends { id: string }>allows only types withid.K extends keyof Tlimits a key to existing properties.- Default.
<T = string>is used when the parameter can't be inferred and isn't passed.- const type parameter.
<const T>infers literal types as if the argument were written withas const.- NoInfer.
NoInfer<T>stops a parameter from taking part in inference, soTis chosen from the other arguments.
function getProp<T, K extends keyof T>(
obj: T,
key: K,
): T[K] {
return obj[key];
}
getProp({ id: 1, name: "Ann" }, "name"); // string
getProp({ id: 1 }, "age"); // errorUtility types
- Partial, Required, Readonly.
- Make every property optional, required or read-only. They work one level deep.
- Pick and Omit.
Pick<User, "id" | "name">keeps the listed keys,Omit<User, "password">removes them.- Record.
Record<Status, string>is an object with exactly these keys and values of one type.- Exclude, Extract, NonNullable.
- Filter a union: remove members, keep members, or remove
nullandundefined. - ReturnType, Parameters, Awaited.
- Take a function's return type, its parameter tuple, and the value inside a promise. Usually used with
typeof fn.
Type-level programming
- keyof and typeof.
keyof Tis the union of keys.typeof valuein a type position takes the type of a variable.- Indexed access.
User["address"]is the type of a property,T[number]is the element type of an array or tuple.- Mapped type.
{ [K in keyof T]: ... }builds a new object type key by key. Modifiers?,readonly,-?and renaming withasare allowed.- Conditional type.
T extends U ? X : Y. Over a naked type parameter it distributes across a union; wrap it in[T]to prevent that.- infer.
- Captures part of a type inside a condition: the element of an array, the value of a promise, a function argument.
- Template literal types.
- Build string types from others, together with
UppercaseandCapitalize, for example event names from keys.
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
type ElementOf<T> =
T extends readonly (infer U)[] ? U : never;
type A = ElementOf<string[]>; // stringClasses and enums
- Access modifiers.
privateandprotectedare checked only by the compiler.#fieldis private at runtime as well.- Parameter properties.
constructor(private name: string)declares and assigns a field at once.- abstract and implements.
- An
abstractclass can't be instantiated and may require methods.implementschecks that a class matches an interface but doesn't add types to it. - enum.
- Creates a real object at runtime; numeric enums also map values back to names. Often replaced with a union of literals or an
as constobject.
Assertions and checks
- as.
- Tells the compiler to trust you. It converts nothing at runtime and allows only related types;
as unknown as Tbypasses even that. - Non-null assertion.
el!removesnullandundefinedfrom the type without any check.- satisfies.
- Checks that a value matches a type but keeps the more precise inferred type.
- Runtime data.
- Types disappear after compilation. JSON, API responses and forms are checked with a schema (Zod, Valibot) or your own guards.
const config = {
port: 3000,
host: "localhost",
} satisfies Record<string, string | number>;
config.port.toFixed(); // ok: port is numberCompiler and configuration
- strict.
- Turns on a group of checks:
strictNullChecks,noImplicitAny,strictFunctionTypesand others. The standard for new projects. - Extra checks.
noUncheckedIndexedAccessaddsundefinedtoarr[i]andobj[key].exactOptionalPropertyTypesseparates a missing property from one set toundefined.- Modules.
moduleResolution: "bundler"for apps built by a bundler,"nodenext"for code run by Node.verbatimModuleSyntaxrequiresimport typefor type-only imports.- Type stripping.
- Node runs
.tsby simply removing types.erasableSyntaxOnlyforbids syntax that needs real code generation:enum,namespace, parameter properties. - Declaration files.
.d.tscontain types only. Types of JS libraries come from@types/*.declare globaland module augmentation extend existing types.- TypeScript 7.
- Since July 2026, the compiler is rewritten in Go and is about 10 times faster. TypeScript 6.0 was the last version written in JavaScript.
Common pitfalls
- Types are erased at runtime: you can't check an interface with
instanceof, and data from an API isn't validated by its type. JSON.parseandresponse.json()returnany, which silently spreads further. Assign the result tounknownand validate it.asdoesn't convert a value:"5" as unknown as numberstays a string.- The excess property check works only for object literals: the same extra field passes through a variable.
- Without
noUncheckedIndexedAccess,arr[10]has the element type, notT | undefined. Object.keys(obj)returnsstring[], not(keyof T)[]: the object may have more keys than its type says.enumand parameter properties produce runtime code and don't work with Node type stripping without extra flags.!andashide a realnull: the error just moves from compile time to runtime.- Methods declared with method syntax
m(x: T): voidare checked bivariantly even understrict. The property syntaxm: (x: T) => voidis checked strictly.