Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 96 ยท Objects and Classes

Object Types in Depth

Go deeper into TypeScript object types - structural typing, assignability, optional vs undefined, readonly and Readonly, index signatures and intersection types.

You met object types in Object Types: property names, optional ? properties, readonly, and index signatures. This lesson explains the rules behind them, the ones that decide whether one object type can be used where another is expected. Once you understand them, many confusing errors (and a few surprising non-errors) make sense.

The central idea is structural typing: TypeScript compares object types by their shape, not by their name. Two types with the same properties are interchangeable, even if they were declared in different files by different people. From there we'll look at what "optional" really means, how far readonly goes, how index signatures interact with known properties, and how intersection types (A & B) combine shapes. These ideas carry straight into the classes chapter that follows.

Structural typing

In languages like Java or C#, a class must say it implements an interface before it can be used as one. That's nominal typing: the name matters. TypeScript is structural: a value fits a type if it has the required properties with compatible types. Nothing has to be declared.

TypeScript Shapes, not names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Point2D and Vector are different names for the same shape, so they're fully interchangeable. point3d has more properties than Point2D needs, and that's fine too: a type describes the minimum a value must have. This is called assignability, and the rule for objects is:

A type S is assignable to a type T if S has every required property of T, and each property's type in S is assignable to the matching property type in T.

Extra properties don't matter, missing ones do. Structural typing matches how JavaScript itself works (it only cares whether p.x exists at runtime), which is why TypeScript chose it. Type Compatibility and Variance covers the remaining edge cases.

Excess property checks: the exception for literals

If extra properties are fine, why does this fail?

TypeScript A typo caught by the excess property check (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The error is TS2561: Object literal may only specify known properties, but 'widht' does not exist in type 'Options'. Did you mean to write 'width'? This is an excess property check, a special extra rule that applies only to fresh object literals, objects written directly where the type is expected. A literal is never referenced anywhere else, so an unknown property there is almost always a typo. With optional properties like width, a misspelling would otherwise be silently ignored.

The check disappears as soon as the object goes through a variable, because then it might be used elsewhere with its other properties:

TypeScript
const opts = { title: 'Settings', widht: 400 };
openWindow(opts); // compiles: opts is not a fresh literal

That's not a bug, just structural typing doing its job; it's also a reason to annotate config objects where you create them (const opts: Options = { ... }), or use satisfies.

There is one more related rule: a weak type is an object type whose properties are all optional. Assigning a value that shares none of its properties is error TS2559 ("Type ... has no properties in common with type ..."), even through a variable. Otherwise every object would fit { width?: number }.

Optional properties vs undefined

width?: number and width: number | undefined look similar but mean different things:

  • width?: number: the property may be missing. Reading it gives number | undefined.
  • width: number | undefined: the property must be present, but its value may be undefined.
TypeScript Missing vs present-but-undefined

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output shows the runtime difference: 'width' in obj is false for {} and true for { width: undefined }, and JSON.stringify drops undefined properties either way. Code that uses in, Object.keys or spreading ({ ...defaults, ...options }) can behave differently for the two. A spread with width: undefined overwrites the default with undefined!

By default TypeScript lets you write undefined into an optional property, which is why a2 compiles. The compiler option exactOptionalPropertyTypes (not part of strict, and off in our editor) closes that gap: with it, width?: number means "missing or a number", and assigning undefined explicitly is an error unless you write width?: number | undefined. Many libraries now ship types that work either way; see The tsconfig.json File.

readonly is shallow, and only a compile-time rule

A readonly property can't be reassigned through that type. Readonly<T> makes every property of a type readonly. Two details matter in practice:

  1. It's shallow. readonly tags: string[] stops you replacing the array, not pushing into it. Use readonly string[] (or ReadonlyArray<string>) for that.
  2. It's not enforced by assignability. A Readonly<User> can be assigned to a User variable, which can then mutate it. readonly is a promise about this reference, not a property of the object.
TypeScript How far readonly goes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Every @ts-expect-error line still runs at runtime (types are erased), which is why the output shows theme changed and both arrays grew. If you need real runtime protection, use Object.freeze. Readonly and Immutability covers deep readonly types and immutable update patterns.

Index signatures and known properties

An index signature describes an object used as a dictionary: { [key: string]: number } accepts any string key. You can mix it with known properties, but every known property must fit the index signature's value type, since obj['name'] and obj.name are the same access:

TypeScript
interface Scores {
  [player: string]: number;
  total: number;      // OK: number fits
  // name: string;    // error TS2411: 'string' is not assignable to 'string' index type 'number'
}

When the index needs mixed values, widen the signature ([key: string]: number | string) or, better, move the dictionary into its own property: { name: string; scores: Record<string, number> }. Index Signatures and Record goes into detail.

The bigger issue is honesty. With an index signature, TypeScript assumes every key exists, so reading a missing key is typed number but is undefined at runtime:

TypeScript Index signatures assume every key exists

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The option noUncheckedIndexedAccess (not in strict, off in our editor) fixes this at the type level: index-signature reads and array element reads become T | undefined, so you're forced to handle the missing case. Most new projects should turn it on; Strict Mode Explained shows its effect.

Intersection types: A & B

An intersection type A & B describes values that are both an A and a B, so they have all the properties of both. Where a union A | B widens what's allowed ("either"), an intersection narrows it ("both").

TypeScript Combining shapes with &

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Intersections are common for mixing in cross-cutting fields (HasId, Timestamps) and in generic helpers like withLabel, where the return type is "whatever came in, plus a label". The spread { ...value, label } is the runtime counterpart of T & { label: string }.

Intersections vs extends

interface StoredPost extends Post, HasId, Timestamps {} describes the same shape. The difference shows up with conflicts. extends checks that the new interface is compatible with its bases and reports an error at the declaration. An intersection never errors; it just combines, and a property that must be both string and number becomes never:

TypeScript Conflicting properties in an intersection (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The error appears only when you try to create a value: main.ts(6,21): error TS2322: Type 'string' is not assignable to type 'never'. Because id can never be satisfied, no value of AB can exist. (When the conflicting properties are literal discriminants, like kind: 'a' and kind: 'b', TypeScript reduces the whole intersection to never.) For this reason, prefer interface ... extends when you're building a hierarchy of object types, since mistakes are reported where you made them, and it's also a little faster for the compiler. Use & for ad-hoc combinations and generic code.

Putting it together

Concept What it means Watch out for
Structural typing Compatible if the shape matches Different "kinds" of string or ID mix freely; see branded types in Type Compatibility
Excess property check Unknown keys in a fresh literal are errors Disappears through a variable
prop?: T May be missing Can still hold undefined without exactOptionalPropertyTypes
readonly / Readonly<T> No reassignment through this type Shallow; not enforced through other references or at runtime
Index signature Any key of that type Lookups claim to always succeed without noUncheckedIndexedAccess
A & B Has everything from both Conflicts become never silently

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. interface P { x: number }. Does const q = { x: 1, y: 2 }; const p: P = q; compile?

    Structural typing ignores extra properties. The excess property check only applies to object literals written directly where P is expected.
  2. 2. interface A { w?: number } and interface B { w: number | undefined }. Which object is valid for B?

    B requires the property to be present; its value may be undefined. {} is only valid for A.
  3. 3. interface S { readonly list: string[] }. Which line compiles?

    readonly is shallow: you can't replace the array, but you can mutate it. Use readonly string[] to forbid push.
  4. 4. What is the type of id in { id: string } & { id: number }?

    An intersection requires both, and nothing is both a string and a number, so id becomes never. No error appears until you try to create a value.
  5. 5. With const prices: Record<string, number> = {} and default strict settings, what is the type of prices['tea']?

    Index signatures assume every key exists. Only noUncheckedIndexedAccess changes the read type to number | undefined.

Summary

  • TypeScript is structurally typed: a value fits an object type if it has all required properties with compatible types; extra properties are allowed.
  • Excess property checks reject unknown keys only in fresh object literals, which catches typos; they vanish through variables. Weak types (all optional) reject values with no shared properties.
  • prop?: T means may be missing; prop: T | undefined means present but maybe undefined. exactOptionalPropertyTypes separates them strictly.
  • readonly and Readonly<T> are shallow, compile-time-only, and don't affect assignability.
  • Known properties must fit an index signature, and index lookups are optimistic unless noUncheckedIndexedAccess is on.
  • Intersections A & B combine shapes; conflicting property types silently become never, so prefer interface extends for hierarchies.

Next: Classes