Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbooks  /  TypeScript
Handbook~15 min readFrontendworked math + runnable code
The TypeScript Handbook

If it fits
the shape.

TypeScript's type system surprises people coming from Java or C#. There, a type match needs a declaration — a class must say implements Duck to count as a Duck. TypeScript doesn't care what you declared; it cares what your object looks like. If it has the properties the type needs, with the right types, it fits — no inheritance, no ceremony. "If it walks like a duck." This structural typing is the single idea that explains almost every "why does/doesn't this compile?" in TypeScript, and this handbook makes the rule exact and runnable.

01

Types by shape

TypeScript is JavaScript with a static type layer checked at compile time and then erased — you get bug-catching and tooling (autocomplete, refactors) at your desk, and plain JavaScript with zero type overhead at runtime. But the thing that defines how it feels is that its type system is structural, not nominal. Compatibility is decided by an object's shape — the properties it has and their types — not by any name or declared inheritance.

This is duck typing made static: "if it walks like a duck and quacks like a duck, it's a duck." An object is compatible with a type if it has what that type asks for, full stop — it never needed to be declared as implementing anything. Define an interface today, and objects you wrote yesterday satisfy it automatically, as long as their shape matches. That single principle — match by shape, not by name — is the key that unlocks TypeScript's behavior. Nearly every question of the form "why is this assignable / why isn't it?" is answered by comparing two shapes, which is exactly what the next section formalizes.

The one-sentence version

TypeScript matches types by shape, not name (structural / duck typing): a value is assignable to a type if it has all the properties that type requires with matching types — so a wider object fits a narrower type, but a missing property never does.

02

The assignability rule

Here's the whole rule in one sentence: a source value is assignable to a target type if, for every property the target requires, the source has that property with a matching type. That's it. Two consequences follow, and they explain most day-to-day TypeScript.

Is source assignable to target?
Wider fitssource has extra props the target doesn't need → assignable (the extras are just ignored).
Missing failssource lacks a property the target requires → not assignable.
Wrong type failssource has the property but with the wrong type → not assignable.
Ruleassignable ⟺ every target prop is present in source with a matching type.

The first consequence trips people up: an object with more properties than the target is still assignable. A function that wants a { x, y } point happily accepts a { x, y, z } — it only ever reads x and y, so the extra z is harmless. A wider object can always stand in where a narrower one is expected. The second is the reverse: an object missing a required property is rejected, because the code might read the property that isn't there. This asymmetry — extra is fine, missing is not — falls directly out of "does the target get everything it asks for?" Once you internalize that one check, TypeScript's assignability stops being mysterious.

03

The excess-property check

If extra properties are always fine, why does TypeScript sometimes complain that 'colour' does not exist in type '{ color: string }'? Because of a deliberate exception: the excess-property check. When you assign a fresh object literal directly to a typed target, TypeScript additionally flags any property the target never declared.

The reason is purely practical: it catches typos. If you write { color: "red", colour: "blue" } against a type that only has color, the structural rule alone would happily accept it (it has color; the extra colour is "just extra"). But almost certainly you meant color and misspelled it, so silently accepting it would hide a bug. The excess-property check is TypeScript deciding that for a fresh literal — where the extra property serves no purpose and probably signals a mistake — it's worth being strict. Crucially, it applies only to object literals assigned directly; the moment the value comes from a variable, the normal "wider is fine" rule takes over again. So the model is: shape-based assignability everywhere, plus one typo-guard tightening for literals. Knowing this explains the otherwise-baffling case where extracting an object to a variable makes a type error disappear.

04

The structural math

Assignability is a simple predicate over the target's required properties — each must exist in the source with a matching type:

assignable(source, target)  ⟺  ∀ (p, t) ∈ target:  p ∈ source ∧ source[p] = t

A wider source (extra props) still satisfies this; a source missing any required p, or with a wrong type at p, fails. Extra is fine, missing is not.

The object-literal check adds one clause — no property outside the target's declared set — to catch typos:

literal_ok(lit, target)  ⟺  assignable(lit, target)  ∧  excess(lit, target) = ∅

For variables, only the first clause applies (wider is fine); for fresh literals, both — so a misspelled property is rejected. The runnable version below implements assignability, missing/excess props, and the literal check.

RUN IT YOURSELF

Structural assignability, modeled

TypeScript's whole type-compatibility story is one predicate over shapes. A source is assignable to a target if every property the target requires exists in the source with a matching type — so an object with extra properties still fits (wider stands in for narrower), but one missing a required property doesn't. Object literals get one extra rule: no excess properties, to catch typos like "colour" for "color". Change the shapes and watch which assignments are legal — this is the type checker's decision, made visible.

CPython · WebAssembly
05

Structural vs nominal

Structural typing is a genuine design choice with trade-offs, best seen against its opposite:

AspectStructural (TypeScript) · Nominal (Java, C#)
Match byShape — any object with the right properties fits · Name — must explicitly implements/extend.
CeremonyLow — existing objects satisfy new interfaces for free · Higher — declare the relationship explicitly.
FlexibilityHigh — great fit for JS's object-literal style · Stricter — types don't accidentally match.
RiskTwo unrelated types with the same shape are interchangeable · Verbosity; more boilerplate.

TypeScript chose structural because it's layering types onto JavaScript, a language built around ad-hoc objects and duck typing — nominal typing would fight the grain of the language. The upside is low ceremony: you define an interface describing a shape, and every value that already has that shape conforms, no edits required. The occasional downside is that two conceptually different types that happen to share a shape (say, a Meters and a Feet both being just number) are freely interchangeable, which can hide a units bug — for those cases you reach for tricks like branded types to simulate nominal typing. But 95% of the time, "match by shape" is exactly what you want, and it's why TypeScript feels lightweight despite adding a whole type system.

06

Pitfalls

The first is the confusing excess-property surprise. You assign an object literal with one extra field and get an error; you extract the exact same object to a variable first and the error vanishes. This looks like a bug in TypeScript but it's the excess-property check working as designed — strict on fresh literals (to catch typos), relaxed on variables (where "wider is fine" applies). Knowing the rule turns a baffling inconsistency into an expected one.

Two bigger ones. Trusting any: typing something as any switches off checking for that value entirely — it's assignable to and from everything, silently — so a stray any can let a whole class of bugs slip through the type system you added precisely to catch them. Prefer unknown (which forces you to narrow before use) and treat any as a last resort. And forgetting types are erased: TypeScript's types vanish at runtime, so they can't validate data that arrives from outside your program — an API response, user input, a JSON parse. Annotating a fetch result as User is a promise, not a check; if the server sends something else, TypeScript won't know. Validate external data at the boundary (with a runtime schema validator) and let types take over inside. The whole handbook rests on one idea worth carrying everywhere: TypeScript matches by shape, not name — a value fits a type when it has what the type asks for — and every surprising assignability result is that rule, plus the literal typo-guard, plus the fact that types are a compile-time story that ends before your program runs.

Worth knowing

The excess-property check is strict on literals, relaxed on variables — that's why extracting to a variable removes an error. Avoid any (it disables checking; prefer unknown), and remember types are erased at runtime, so validate external data at the boundary.

By the numbers

Worked example: eight assignments, traced through the rule

One target, interface User { id: number; name: string; email?: string }, and eight values assigned to it. Each verdict below is what tsc --strict actually prints. Apply the page’s two checks in order: does every required property exist with the right type, and, for a fresh literal only, is anything extra?

#Assignment to UserCheck that decidesVerdict
1{ id: 1, name: "Ana" } via a variableRequired id, name present; email? is optionalOK
2variable holding { id: 1, name: "Ana", admin: true }Wider is fine; not a fresh literalOK
3the same object written as a literalExcess-property checkError: 'admin' does not exist in type 'User'
4{ id: "1", name: "Ana" }Wrong type at idError: Type 'string' is not assignable to type 'number'
5{ name: "Ana" }Missing required idError: Property 'id' is missing
6variable holding { id: 1, nmae: "Ana" }Missing required nameError, even from a variable
7variable holding { id: 1, name: "Ana", emial: "a@x.io" }All required present; extra is fineOK, and the typo is lost
8the same object written as a literalExcess-property checkError: Did you mean to write 'email'?

Row 6 shows why the typo guard matters less for required fields: misspell name and the missing name is caught anyway. Row 7 is the real hole. A typo in an optional property, arriving through a variable, passes silently, and email is simply undefined at runtime. The literal check in row 8 is the only thing that catches it, which is why building objects inline at the call site is safer than assembling them elsewhere. One more variant: { id: 1, name: "Ana", email: undefined } is OK by default, but fails under exactOptionalPropertyTypes, which separates “absent” from “present but undefined”.

Trade-offs

Cost and trade-offs: what each tool costs at compile time and at runtime

Here Time means the cost while you build and type-check, Space means what reaches the shipped JavaScript.

CaseTimeSpaceWhy
Plain annotations and interfacesChecked on every compileZero bytes: erasedThe default. Catches shape bugs inside your code and nothing outside it.
anyFree: checking switched offZero bytesSilences errors by giving up the check, and spreads to whatever touches it.
unknown + narrowingYou write the type guardsOnly your typeof/in checksSafe for untyped input: nothing compiles until you have proved the shape.
Branded typesA cast at each creation pointZero bytesnumber & { __brand: "m" } makes Meters and Feet incompatible. Verified: tsc rejects assigning one to the other.
Runtime schema validatorWrite or derive a schemaLibrary bytes, plus a parse per valueThe only option that checks data from outside. Use it at boundaries, not on every internal call.
enum vs union of literalsSimilarA regular enum emits a runtime object; a union emits nothingA union like "draft" | "live" gives the same checking for zero bytes.
Deep conditional and recursive typesSlow checks, editor lagZero bytesThe compiler gives up past a depth limit (“excessively deep”). Clever types slow the whole team’s editor.

The pattern: the type system is free at runtime and costs you at compile time, until data crosses a boundary. There, only code that runs can check anything, so you pay in bytes and CPU, once, at the edge.

In the wild

Where this shows up in real-world code and interviews

  • Test doubles for free

    Because matching is by shape, a test can pass { getUser: async () => fakeUser } wherever a UserRepo is expected. No mocking framework, no subclass. Only the methods the code under test calls need to exist.

  • Typing JavaScript you did not write

    Declaration files (.d.ts), including the community @types/* packages, describe the shape of plain JS libraries after the fact. That only works because types are structural: the library never declared that it implements anything.

  • API boundaries

    A fetch result typed as User is the row 7 hole at scale: a renamed field on the server becomes undefined in production with no compile error. Teams parse responses through a runtime schema and derive the static type from it, so the two cannot drift.

  • The interview version

    Expect “why does this compile?” puzzles: a wider object accepted, the error that disappears when a literal moves into a variable, any versus unknown. Go makes a good comparison: its interfaces are also satisfied implicitly, by method set, while Java and C# need an explicit implements.

Self-check

Check yourself

function draw(p: { x: number; y: number }) is called as draw(pt) where pt is a variable holding { x: 1, y: 2, z: 3 }. Does it compile? What if you call draw({ x: 1, y: 2, z: 3 })?

The variable call compiles: every required property is present and the extra z is ignored. The inline call fails. It is a fresh literal, so the excess-property check flags z. Same object, different verdict, because only literals get the typo guard.

A config object assembled in one file sets retires: 3 instead of retries: 3, and retries is optional in the Config type. Will tsc catch it when the object is passed in?

No, if the object reaches the call through a variable. Everything required is present, and the extra retires is allowed. The code silently uses the default retry count. Typing the object at its declaration (const cfg: Config = { … }) makes it a checked literal, and the typo is caught there.

type Meters = number and type Feet = number. Can you pass a Feet where a Meters is expected, and how would you stop it?

Yes. Both aliases are just number, the same shape, so they are interchangeable. Add a brand that differs, number & { __brand: "m" } versus "ft", and the shapes no longer match, so tsc rejects the mix-up at zero runtime cost.

JSON.parse returns any. You assign it to const u: User. What has TypeScript verified about u?

Nothing. any is assignable to everything, and types are erased, so no check runs. Type the result as unknown instead and the compiler forces you to narrow it, or better, parse it through a runtime validator that returns a real User.

Frequently asked

Quick answers

What is TypeScript?

JavaScript plus a static type layer checked at compile time and erased before runtime — bug-catching and tooling with zero runtime cost.

What is structural typing?

Compatibility by shape, not name (duck typing): an object fits a type if it has the required properties with matching types, no declaration needed.

Why is an object with extra props assignable?

Assignability only needs the target's required properties present; extras are ignored — except a fresh object literal is checked for excess to catch typos.

Structural vs nominal?

Structural matches by shape (flexible, low ceremony); nominal (Java/C#) requires an explicit implements/extends declaration (stricter, more verbose).

Finished this one? 0 / 209 Handbooks done
NextThe React Handbook Next on the “The languages you ship in” ladder · rung 3 of 7

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.