← Fundamentals
Fundamentals

Constructors and creating values

How does a new value get its initial state?

Establish the initial fields, defaults, and invariants of each newly created value.

Outcome

Predict what an omitted field holds, keep invariants inside the constructor or factory, assign the field rather than a parameter, and build each new value from its own copy of a template.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Constructor
Code that runs when a value is created and sets its initial state.
Factory function
An ordinary function that builds and returns a new value, often checking its inputs.
Invariant
A rule every value of a type must satisfy, such as nights between 1 and 14.
Default value
The value a field gets when the creator does not give one.
Builder
An object that collects settings and produces new values from them.

Construction establishes initial state

Construction turns supplied values and defaults into an initial state. A literal, constructor or factory may take different paths to that state. The language’s initialization rules determine what must be supplied; the application decides which resulting states are acceptable.

An invariant is a rule that must hold whenever a completed value is used. Put its enforcement where the relevant creation paths can apply it, and account for paths that bypass that enforcement. When defaults include mutable parts, also decide whether each new value should share them or receive independent state.

01Omitted fields

What a field holds when the literal leaves it out

A bed and breakfast creates bookings from typed-in lines: some give the number of nights and some do not, every stay must be between 1 and 14 nights, and each booking starts from a template of extras. All of that is decided at the moment a value is created.

The import sometimes receives only a guest’s name. Before installing the one-night business default, check what this native construction already puts in nights.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type Booking = { guest: string; nights?: number };

const booking: Booking = { guest: "ana" };

console.log(booking.guest, booking.nights);
What is printed?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc --noEmit --strict main.ts && node main.ts

Use the selected native command from the first reading. For each probe, consider both whether construction is accepted and what initial state it produces.

02Constructors and factories

A constructor or factory is where invariants belong

The room list needs a trimmed name and a stay from 1 to 14 nights. This creation path receives " ana " and 30: predict the stored booking rather than just its raw input.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
class Booking {
  readonly guest: string;
  readonly nights: number;

  constructor(guest: string, nights: number) {
    this.guest = guest.trim();
    this.nights = Math.min(Math.max(nights, 1), 14);
  }
}

const booking = new Booking("  ana ", 30);

console.log(`[${booking.guest}] ${booking.nights}`);
What is printed?

03Defaults that go wrong

Defaults can override input, hide a missing value or parse as a declaration

An import adapter can also construct a value through defaults or literal syntax. Check whether those paths preserve an explicit choice and the booking rules; predict the selected native result.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type Booking = { guest: string; nights: number };

const defaults = { nights: 1 };
const input = { guest: "ana", nights: 3 };

const booking: Booking = { ...input, ...defaults };

console.log(booking.guest, booking.nights);
What is printed?

04Repair the bed and breakfast

Default nights, the stay’s range, then a template

Repair the booking-import utilities: apply a default only when nights is absent, create the three-field stay with its bounded nights and unchanged guest count, then construct independent bookings from the reusable extras template.

Each file contains its imports, reader and complete caller.

Repair the bed and breakfast

Keep supplied nights or default missing input, store the bounded stay in the correct field, then preserve a reusable extras template across builds.

  1. easy · F-CTOR-V4-1 Default the nights
  2. medium · F-CTOR-V4-2 Keep the stay in range
  3. hard · F-CTOR-V4-3 Build bookings from a template
In the frontend A prop fallback handles absence; it does not validate a booking. Optional

A booking preview may receive no nights prop while an import is being prepared. Both component examples use 1 only when the prop is missing or undefined. A supplied 0 remains 0; the booking-construction path must apply its separate 1-to-14 rule.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
export default function StayPreview({ nights = 1 }: { nights?: number }) {
  return <p>{nights} nights</p>;
}

The default parameter value applies to an omitted or undefined prop. It preserves an explicit numeric value; this display component does not construct or validate the domain Booking.

Sources: React: specifying a default prop,Svelte: prop fallback values.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.