Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
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.
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.
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.
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.
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.
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.
The structural math
Assignability is a simple predicate over the target's required properties — each must exist in the source with a matching type:
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:
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.
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.
Structural vs nominal
Structural typing is a genuine design choice with trade-offs, best seen against its opposite:
| Aspect | Structural (TypeScript) · Nominal (Java, C#) |
|---|---|
| Match by | Shape — any object with the right properties fits · Name — must explicitly implements/extend. |
| Ceremony | Low — existing objects satisfy new interfaces for free · Higher — declare the relationship explicitly. |
| Flexibility | High — great fit for JS's object-literal style · Stricter — types don't accidentally match. |
| Risk | Two 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.
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.
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.
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 User | Check that decides | Verdict |
|---|---|---|---|
| 1 | { id: 1, name: "Ana" } via a variable | Required id, name present; email? is optional | OK |
| 2 | variable holding { id: 1, name: "Ana", admin: true } | Wider is fine; not a fresh literal | OK |
| 3 | the same object written as a literal | Excess-property check | Error: 'admin' does not exist in type 'User' |
| 4 | { id: "1", name: "Ana" } | Wrong type at id | Error: Type 'string' is not assignable to type 'number' |
| 5 | { name: "Ana" } | Missing required id | Error: Property 'id' is missing |
| 6 | variable holding { id: 1, nmae: "Ana" } | Missing required name | Error, even from a variable |
| 7 | variable holding { id: 1, name: "Ana", emial: "a@x.io" } | All required present; extra is fine | OK, and the typo is lost |
| 8 | the same object written as a literal | Excess-property check | Error: 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”.
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.
| Case | Time | Space | Why |
|---|---|---|---|
| Plain annotations and interfaces | Checked on every compile | Zero bytes: erased | The default. Catches shape bugs inside your code and nothing outside it. |
any | Free: checking switched off | Zero bytes | Silences errors by giving up the check, and spreads to whatever touches it. |
unknown + narrowing | You write the type guards | Only your typeof/in checks | Safe for untyped input: nothing compiles until you have proved the shape. |
| Branded types | A cast at each creation point | Zero bytes | number & { __brand: "m" } makes Meters and Feet incompatible. Verified: tsc rejects assigning one to the other. |
| Runtime schema validator | Write or derive a schema | Library bytes, plus a parse per value | The only option that checks data from outside. Use it at boundaries, not on every internal call. |
enum vs union of literals | Similar | A regular enum emits a runtime object; a union emits nothing | A union like "draft" | "live" gives the same checking for zero bytes. |
| Deep conditional and recursive types | Slow checks, editor lag | Zero bytes | The 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.
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 aUserRepois 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
fetchresult typed asUseris the row 7 hole at scale: a renamed field on the server becomesundefinedin 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,
anyversusunknown. Go makes a good comparison: its interfaces are also satisfied implicitly, by method set, while Java and C# need an explicitimplements.
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.
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).
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Handbooks
- The Agentic AI Interview HandbookTwenty topics every senior AI engineer should be able to reason about live — from eval pipelines to reliability patterns for generative systems.Read →
- The Senior AI Engineer Interview Handbook60 questions across architecture, production incidents, agentic systems, RAG, evals, cost, safety, and leadership — what staff-level AI interviewers actually probe for.Read →
- 50 Angular Interview QuestionsA visual handbook covering components, change detection, RxJS, signals, routing, forms, performance, and testing — what interviewers actually probe for in senior Angular roles.Read →
- 50 Python Interview QuestionsFundamentals to advanced: data structures, OOP, iterators & generators, the GIL, asyncio, memory, testing, and the standard library — a visual walk through everything a Python interview touches.Read →
- 51 LLM Evals Interview QuestionsGolden sets, LLM-as-judge, regression testing, offline vs online evals, RAG evals, agent evals, red-teaming, and observability — demystified for interviews and production.Read →
- The Agent Evaluations HandbookA self-contained handbook on evaluating AI agents — theory, interactive widgets, and practical guidance. Trajectory evals, tool-use scoring, LLM-as-judge, observability, and reliability for PMs, engineers, and founders.Read →