TypeScript Interface vs Type Alias, and Object Types

Optional and readonly properties, index signatures, Record and intersections, and when an interface beats a type alias.

In this chapter

Object types, interfaces and type aliases

Object types: common questions

Should I use type or interface in TypeScript?

Both describe object shapes. Interfaces can be extended and merged, which suits public APIs. Type aliases can also name unions, tuples and mapped types. Pick one default for objects and stay consistent.

More on Everyday types

Keep learning

Overview

chapters · everyday types Object types, interfaces and type aliases Describe the shape of an object: which keys exist, which are optional, which never change.

1. The problem: a lookup that promises every key

A coffee shop keeps prices by product. One product (mocha) is missing from the table. any string key, and its value is a number index signature: any string key number (says the checker) The type promises a number for every key, so TypeScript allows prices.mocha. But mocha is not in the object, so the value is undefined. Runtime: TypeError: Cannot read properties of undefined. Record over a known set of keys 'latte' | 'flatWhite' | 'mocha' is a union: "one of these three strings". Record<Sku, number> means "an object with exactly these keys, each a number". Mocha is in Sku but not in the object, so the build fails before the app runs.

2. Object types: optional and readonly

An interface gives a name to an object shape. ? after a key means "may be left out". readonly means "can be set once, never reassigned".

a todo item

string | undefined Cannot assign to 'id' because it is a read-only property. 't.dueDate' is possibly 'undefined'. Line 10 fails because id is marked readonly. Line 11 fails because dueDate? may be missing, and you cannot call .slice on undefined. Check first: t.dueDate?.slice(0, 4) (?. stops and gives undefined if the left side is missing). title: string must exist, any string dueDate?: string may be left out readonly id: string string, no reassign checked at build only readonly tags: string[] tags.push() still works readonly is shallow: it locks the property, not the array inside it Does line 4 compile? no: items is read-only

3. Index signatures and better options

any key, all values T index signature n: number (really undefined) Any key is accepted, and every read says number. chai is not in the object, so n is really undefined. Typos and missing keys slip through. Record<Union, T> Property 'chai' does not exist on type 'Record<Sku, number>'. 'stock.mocha' is possibly 'undefined'. Partial<…> makes every key optional. So mocha may be missing, and a read gives number | undefined. You must check before calling toFixed. n: number | undefined Map<string, number> is a built-in key → value store. Use it when keys arrive at runtime (user ids, cart lines). get() returns number | undefined, because the key may be missing. Keys known ahead of time Record<Union, T> or a plain interface Keys from runtime data Map<K, V> Numeric keys JS turns them into strings. Use an array or Map. Truly open bag of strings Index signature is fine, e.g. HTTP headers

4. Intersections: combine shapes with &

An intersection (A & B) has every property of A and every property of B. all five properties + id When both sides define the same key with clashing types, nothing fits that key. TypeScript calls that never: the empty type, no value fits.

A clash does not error. It quietly becomes never.

two shapes id must satisfy both no value is both

5. interface vs type

Both interface and type can name an object shape. The difference shows when two shapes disagree on a key. The setup: User says id is a string. Admin tries to say id is a number. type + & : the clash hides until you use it id: string & number → never Type 'string' is not assignable to type 'never'. & means "must be both". Nothing can be a string and a number, so id becomes never. The error only appears when you create an Admin. interface extends: the clash is caught at once Interface 'Admin' incorrectly extends interface 'User'. Types of property 'id' are incompatible. Type 'number' is not assignable to type 'string'. extends means "Admin is a kind of User". A number id breaks that promise, so the declaration itself fails.

Why the left side says 'never'

& merges both shapes, key by key the same key appears twice, so its types are joined with & id: string & number no value is a string AND a number at the same time so 'u1' (a string) cannot go into id Type 'string' is not assignable to type 'never'. & (intersection) Combines blindly. A conflict quietly becomes never, and you find out later, far from the cause. Checks that the child fits the parent. A conflict is an error on the line that caused it. object shapes unions: 'card' | 'cash' tuples, functions, mapped types extend another shape reports conflicts at declaration declaration merging (reopen it) 'some': an interface can describe a call signature or extend an array, but not a union or a mapped type (a type built by looping over keys). Declaration merging: if you write interface X twice, TypeScript joins both into one. A type name can be declared only once.

declaration merging: two interfaces, one type

ok: Window now has analyticsId Duplicate identifier 'Theme'. Line 1 adds a key to the browser's built-in Window interface (defined in lib.dom, TypeScript's browser types). Line 6 fails because Theme already exists and type aliases cannot be reopened. Use interface Use type Pick one default for object shapes and stay consistent. Both are fine.

Remember

key?: T means the key may be absent: reads give T | undefined. readonly is shallow and build-time only. Index signatures claim every key exists. Prefer Record over a union, or Map. Unions need type. Augmenting needs interface. ! Cheat code

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.