DiscoveryVIP / TypeScript AcademyHelp

40. Modeling application states

Module 8 · approximately 20 minutes

Open Interactive Lesson

Discover and predict

What does modeling application states let the compiler check, and what still needs a runtime test?

Understand

A state model should make invalid combinations difficult to represent. A loading state should not simultaneously require successful data or a failure message. Discriminated unions express those alternatives and help rendering logic stay aligned. They do not automatically schedule asynchronous work or prevent stale responses; those are runtime design concerns.

Important source operations

Line 1: type State={status:"idle"}|{status:"loading"}|{status:"ready";items:string[]}|{status:"error";message:string};
This declaration describes a static contract and does not construct or validate runtime data. Actual checker declaration information: State: { status: "idle"; } | { status: "loading"; } | { status: "ready"; items: string[]; } | { status: "error"; message: string; }.
Line 2: function describe(state:State):string {
Follow the value relationship and inspect compiler information at this source position. Actual checker declaration information: describe: (state: State) => string; state: { status: "idle"; } | { status: "loading"; } | { status: "ready"; items: string[]; } | { status: "error"; message: string; }.
Line 3: if(state.status === "ready") return state.items.join(", ");
The return expression must satisfy the declared or inferred signature. Its business meaning still needs independent tests.
Line 4: if(state.status === "error") return state.message;
The return expression must satisfy the declared or inferred signature. Its business meaning still needs independent tests.
Line 5: return state.status;
The return expression must satisfy the declared or inferred signature. Its business meaning still needs independent tests.
Line 6: }
Follow the value relationship and inspect compiler information at this source position.
Line 7: console.log(describe({status:"ready",items:["HTML","CSS"]}));
Observe the actual runtime value. A log is evidence for this input, not proof of every permitted value.

Working concept in practice

A state model should make invalid combinations difficult to represent. A loading state should not simultaneously require successful data or a failure message. Discriminated unions express those alternatives and help rendering logic stay aligned. They do not automatically schedule asynchronous work or prevent stale responses; those are runtime design concerns.

main.ts

type State={status:"idle"}|{status:"loading"}|{status:"ready";items:string[]}|{status:"error";message:string};
function describe(state:State):string {
  if(state.status === "ready") return state.items.join(", ");
  if(state.status === "error") return state.message;
  return state.status;
}
console.log(describe({status:"ready",items:["HTML","CSS"]}));

Exact authored reference result

{
  "diagnostics": [],
  "logs": [
    "HTML, CSS"
  ],
  "error": null
}

Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.

Investigate the compiler or runtime fault

Predict the result of the supplied wrong operation. Read actual compiler feedback; if it compiles, investigate the real runtime mismatch instead. Fault: {status:"ready"}

main.ts

type State={status:"idle"}|{status:"loading"}|{status:"ready";items:string[]}|{status:"error";message:string};
function describe(state:State):string {
  if(state.status === "ready") return state.items.join(", ");
  if(state.status === "error") return state.message;
  return state.status;
}
console.log(describe({status:"ready"}));

Exact authored reference result

{
  "diagnostics": [
    {
      "code": 2345,
      "category": "Error",
      "message": "Argument of type '{ status: \"ready\"; }' is not assignable to parameter of type 'State'.\n  Property 'items' is missing in type '{ status: \"ready\"; }' but required in type '{ status: \"ready\"; items: string[]; }'.",
      "file": "main.ts",
      "line": 7,
      "column": 22,
      "start": 312,
      "length": 16
    }
  ],
  "logs": [],
  "error": null
}

Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.

A compiler-clean behavioral counterexample

A type-compatible text value differs from the intended content. The compiler checks type relationships, not the accuracy of arbitrary text. This intentionally incorrect program demonstrates why runtime tests remain necessary.

main.ts

type State={status:"idle"}|{status:"loading"}|{status:"ready";items:string[]}|{status:"error";message:string};
function describe(state:State):string {
  if(state.status === "ready") return state.items.join(", !");
  if(state.status === "error") return state.message;
  return state.status;
}
console.log(describe({status:"ready",items:["HTML","CSS"]}));

Exact authored reference result

{
  "diagnostics": [],
  "logs": [
    "HTML, !CSS"
  ],
  "error": null
}

Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.

An executable behavior contract

Capture the actual observable result and assert the independently authored expected output. This optional professional test pattern introduces helper/rest/async syntax; focus on the primary example first if those concepts are new.

main.ts

const __observed:string[]=[];
function __capture(...values:unknown[]):void{__observed.push(values.map(value=>typeof value==="string"?value:typeof value==="undefined"?"undefined":typeof value==="number"&&!Number.isFinite(value)?String(value):JSON.stringify(value)??String(value)).join(" "));}
type State={status:"idle"}|{status:"loading"}|{status:"ready";items:string[]}|{status:"error";message:string};
function describe(state:State):string {
  if(state.status === "ready") return state.items.join(", ");
  if(state.status === "error") return state.message;
  return state.status;
}
__capture(describe({status:"ready",items:["HTML","CSS"]}));
async function verifyContract():Promise<void>{await new Promise<void>(resolve=>setTimeout(resolve,15));const expected:string[]=["HTML, CSS"];if(JSON.stringify(__observed)!==JSON.stringify(expected))throw new Error("Behavior contract failed");console.log("Contract verified");}
verifyContract().catch(error=>console.log(error instanceof Error?error.message:String(error)));

Exact authored reference result

{
  "diagnostics": [],
  "logs": [
    "Contract verified"
  ],
  "error": null
}

Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.

Transfer to another useful feature

Apply the topic in a different small task. Predict the output and identify the type/runtime boundary before editing.

main.ts

type SaveState={status:"unsaved"}|{status:"saved";id:string};
function savedId(state:SaveState):string{return state.status==="saved"?state.id:"No saved ID";}
console.log(savedId({status:"unsaved"}));

Exact authored reference result

{
  "diagnostics": [],
  "logs": [
    "No saved ID"
  ],
  "error": null
}

Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.

Build and test

Repair the supplied source so it compiles under the lesson settings and produces HTML, CSS. Equivalent implementations may pass the observable contract.

Hint 1

Read the first meaningful diagnostic and its source location, or compare the first runtime mismatch when the program compiles.

Hint 2

The exercise changes {status:"ready",items:["HTML","CSS"]} to {status:"ready"}. Determine whether the contract, caller or business operation is wrong.

Hint 3

Restore {status:"ready",items:["HTML","CSS"]} or implement an equivalent correct contract. Do not hide the issue with any or an unjustified assertion; run the stated behavior check.

Explain, reflect and extend

Explain which evidence came from the compiler and which came from execution. Give a second input and a predicted result. What assumption could still fail outside this example?

Extend the useful feature with a boundary case and one invalid external input. Write the expected behavior first, then verify it using actual diagnostics and tests.

Troubleshooting

Verify the active filename, first diagnostic, actual inferred/flow type and emitted output. A type error blocks emission in this lab; an empty runtime pane is not a fabricated success. Browser examples require the DOM preview, while worker execution has no document. Project imports must refer to supplied relative files. Check runtime validation and logical operators when clean compilation still produces the wrong result.

Next full lesson