Catalog My learning Blog
Frontend Developer Course: 100 Concepts in 100 Days · Phase 5 · Lesson 41 · 6 min read

TypeScript Structural Typing Explained

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: Shapes, Brands and Strictness
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Explain what TypeScript checks and what it does not, how structural typing decides compatibility by shape rather than name, how type inference reduces annotations, the difference between interfaces and type aliases, and why strict compiler options and avoiding any are what make the type system useful.

Concept Explanation

TypeScript is JavaScript with static types that are checked at compile time and then erased. The compiler reads your code, infers and checks types, reports errors and emits ordinary JavaScript with the type annotations removed. Nothing about the types exists at run time: there are no type checks when the code runs, a value from an API is whatever the server sent, and a cast tells the compiler to trust you without verifying anything. This is the single most important thing to understand about TypeScript, and Day 45 builds directly on it.

TypeScript's type system is structural. Two types are compatible if their shapes are compatible, not because they share a name or an inheritance relationship. If a function expects an object with a name string, any object that has a name string satisfies it, including objects with extra properties. This matches how JavaScript is actually written, with plain objects passed around freely, and contrasts with nominal type systems such as those in C# and Java, where a class must explicitly declare that it implements an interface.

Structural typing has one guard rail worth knowing: excess property checks. When you pass an object literal directly where a type is expected, TypeScript reports properties that the type does not declare, because a typo such as colour instead of color is far more likely than an intentional extra. The same object assigned to a variable first and then passed is accepted, because it is no longer fresh. When you genuinely need two structurally identical types to be incompatible, such as user ids and order ids that are both strings, a branded type adds a phantom property that only your constructor function can produce.

Most types do not need to be written. TypeScript infers variable types from initializers, return types from return statements and callback parameter types from context, so annotations are mainly needed at boundaries: function parameters, exported APIs and data from outside. Interfaces and type aliases both describe object shapes. Interfaces can be extended and merged by redeclaration, which suits public object contracts; type aliases can also express unions, intersections, tuples and computed types. Teams commonly pick one style for objects and use type aliases for everything else.

The value of TypeScript depends heavily on configuration. The strict flag enables strictNullChecks, which makes null and undefined separate types so the compiler forces you to handle them, and noImplicitAny, which reports values whose type could not be inferred. Options like noUncheckedIndexedAccess add undefined to array and record lookups, catching out-of-range bugs. The type any switches checking off entirely and spreads silently through code. unknown is its safe counterpart: anything can be assigned to it, but you must narrow it before using it.

ConceptMeaningExample
Type erasureTypes vanish at run timeNo checks on API data
Structural typingCompatible if shapes matchAny object with name: string fits
Excess property checkFresh literals cannot add unknown keysCatches colour instead of color
InferenceTypes derived from codeconst n = 5 is a number
interfaceExtendable object contractinterface User { id: string }
type aliasAny type, including unionstype Id = string or number
strict modeNull checks, no implicit anyForces handling of undefined
unknown versus anyMust narrow versus no checkingPrefer unknown for untrusted data

Worked Example: Shapes, Brands and Strictness

The snippets show structural compatibility, an excess property error, a branded id that prevents mixing ids, and how strict null checks catch a crash before it ships.

TypeScript
interface HasName { name: string }

function greet(x: HasName) { return `Hello, ${x.name}`; }

const user = { id: 'u1', name: 'Ana', role: 'admin' };
greet(user);                          // OK: extra properties are fine for a non-fresh object
// greet({ name: 'Sam', nmae: 'x' }); // Error: object literal may only specify known properties

// Branded ids: structurally both strings, but not interchangeable
type UserId = string & { readonly __brand: 'UserId' };
type OrderId = string & { readonly __brand: 'OrderId' };
const asUserId = (s: string) => s as UserId;            // the only place a cast is allowed
const asOrderId = (s: string) => s as OrderId;

function loadUser(id: UserId) { /* ... */ }
const orderId = asOrderId('o-42');
// loadUser(orderId);                 // Error: OrderId is not assignable to UserId
loadUser(asUserId('u-7'));

// strictNullChecks catches a real crash
function initials(fullName: string | undefined) {
  // return fullName.split(' ').map((p) => p[0]).join('');   // Error: possibly undefined
  return (fullName ?? '').split(' ').map((p) => p[0] ?? '').join('');
}

// unknown forces narrowing, any does not
function parseBad(json: string): any { return JSON.parse(json); }
parseBad('{}').user.name.toUpperCase();   // compiles, crashes at run time

function parseSafe(json: string): unknown { return JSON.parse(json); }
const data = parseSafe('{}');
// data.user;                         // Error: data is of type unknown
JSON
{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "noImplicitOverride": true,
    "verbatimModuleSyntax": true
  }
}

The p[0] ?? '' in initials is required by noUncheckedIndexedAccess, which knows that indexing a string or array can return undefined. That one option catches a surprising number of edge cases with empty inputs.

TypeScript reads annotated source, infers and checks types by shape, and emits plain JavaScript with every type removed. At run time nothing checks the data, so an API response typed as User can be anything.
TypeScript reads annotated source, infers and checks types by shape, and emits plain JavaScript with every type removed. At run time nothing checks the data, so an API response typed as User can be anything.

Real-World Examples

  • Airbnb's engineering team reported in a 2019 talk that a postmortem analysis found 38 percent of their production bugs could have been prevented by TypeScript, which was a key argument in their decision to adopt it across their frontend codebase.
  • TypeScript's design goals, published in the project's wiki, explicitly state that it does not aim for a provably sound type system and that it imposes no run-time overhead, which is why types are erased and why validation at boundaries remains your responsibility.
Key TakeawaysTypeScript checks the shapes of values at compile time and erases all types at run time, so it never validates real data arriving from outside. Compatibility is structural, with excess property checks for fresh literals and brands when you need nominal distinctions. Let inference do most of the work, annotate boundaries, enable strict and noUncheckedIndexedAccess, and prefer unknown to any for anything untrusted.

Review Questions & Answers

Type compatibility is determined by the members a type has, not by its name or declared relationships. Any value with the required properties of compatible types satisfies a type, even if it was never declared as that type and has extra properties.

Types are erased when TypeScript compiles to JavaScript, so there are no checks at run time. Declaring that a fetch result is a User only tells the compiler to assume it; the actual data can be anything, so it must be validated at the boundary.

Both accept any value. any disables checking, so you can call anything on it and errors spread silently. unknown allows no operations until you narrow it with checks such as typeof, instanceof or a validation function, which forces safe handling.

When values have the same underlying type but must not be mixed, such as user ids and order ids that are both strings, or amounts in different currencies. The brand makes them structurally different, so the compiler rejects passing one where the other is expected.