Nested object models
Concept and syntax
Use a named type for a nested record when it has its own meaning. A shipment can require an address, and the address can require city and postalCode. The outer contract checks the nested value against the inner shape. Reading shipment.address.city follows two properties. Keep postal codes as strings when leading zeros matter; a number would lose that textual information.
Working example
Compile standalone examples in a fresh directory with tsc --strict --target ES2022 --module commonjs --noEmitOnError main.ts, then node main.js.
interface Address { city: string; postalCode: string; }interface Shipment { id: number; address: Address; }const shipment: Shipment = { id: 2, address: { city: "Lund", postalCode: "01234" } };console.log(shipment.address.city, shipment.address.postalCode);Expected output (one line per log):
Lund 01234Common mistake
Intentionally invalid; check this snippet separately. Do not run it.
interface Address { city: string; postalCode: string; }interface Shipment { address: Address; }const shipment: Shipment = { address: { city: "Lund" } };Expected compiler diagnostic: TS2741. The nested address is missing its required postalCode. Fill in the nested contract, not an unrelated top-level field.
Practice and recap
Model a profile with a nested contact record. Omit one required inner field and identify the precise failing contract.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Nested object models — knowledge check
Check the concept, apply it to a new choice, and interpret a compiler diagnostic.
Which expression reads the nested city?
Why model postalCode as string here?
Which field is missing from the nested address?
interface Address { city: string; postalCode: string; }interface Shipment { address: Address; }const shipment: Shipment = { address: { city: "Lund" } };