DiscoveryVIP / TypeScript AcademyHelp

80. Building typed user interfaces

Module 16 · approximately 20 minutes

Open Interactive Lesson

Discover and predict

What does building typed user interfaces let the compiler check, and what still needs a runtime test?

Understand

A typed UI connects a validated model to real DOM updates and events. Type-safe data does not guarantee accessible markup, sensible focus or clear status messages. Use textContent for untrusted text, native controls for actions and tests that observe actual interaction. This small render function creates real list items rather than printing a JSON-only simulation of an interface.

Important source operations

Line 1: type Task={title:string;done:boolean};
This declaration describes a static contract and does not construct or validate runtime data. Actual checker declaration information: Task: { title: string; done: boolean; }.
Line 2: const tasks:Task[]=[{title:"Read source",done:false},{title:"Test output",done:true}];
Follow the value relationship and inspect compiler information at this source position. Actual checker declaration information: tasks: Task[].
Line 3: const list=document.createElement("ul");
Follow the value relationship and inspect compiler information at this source position. Actual checker declaration information: list: HTMLUListElement.
Line 4: tasks.forEach(task=>{const item=document.createElement("li");item.textContent=task.title;list.append(item);});
Follow the value relationship and inspect compiler information at this source position. Actual checker declaration information: task: { title: string; done: boolean; }; item: HTMLLIElement.
Line 5: document.body.append(list);
Follow the value relationship and inspect compiler information at this source position.
Line 6: console.log(list.children.length);
Observe the actual runtime value. A log is evidence for this input, not proof of every permitted value.

Working concept in practice

A typed UI connects a validated model to real DOM updates and events. Type-safe data does not guarantee accessible markup, sensible focus or clear status messages. Use textContent for untrusted text, native controls for actions and tests that observe actual interaction. This small render function creates real list items rather than printing a JSON-only simulation of an interface.

main.ts

type Task={title:string;done:boolean};
const tasks:Task[]=[{title:"Read source",done:false},{title:"Test output",done:true}];
const list=document.createElement("ul");
tasks.forEach(task=>{const item=document.createElement("li");item.textContent=task.title;list.append(item);});
document.body.append(list);
console.log(list.children.length);

Exact authored reference result

{
  "diagnostics": [],
  "logs": [
    "2"
  ],
  "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: done:"false"

main.ts

type Task={title:string;done:boolean};
const tasks:Task[]=[{title:"Read source",done:"false"},{title:"Test output",done:true}];
const list=document.createElement("ul");
tasks.forEach(task=>{const item=document.createElement("li");item.textContent=task.title;list.append(item);});
document.body.append(list);
console.log(list.children.length);

Exact authored reference result

{
  "diagnostics": [
    {
      "code": 2322,
      "category": "Error",
      "message": "Type 'string' is not assignable to type 'boolean'.",
      "file": "main.ts",
      "line": 2,
      "column": 42,
      "start": 80,
      "length": 4
    }
  ],
  "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 Task={title:string;done:boolean};
const tasks:Task[]=[{title:"Read source",done:false},{title:"Test output",done:true}];
const list=document.createElement("ul!");
tasks.forEach(task=>{const item=document.createElement("li");item.textContent=task.title;list.append(item);});
document.body.append(list);
console.log(list.children.length);

Exact authored reference result

{
  "diagnostics": [],
  "logs": [],
  "error": "InvalidCharacterError: \"ul!\" did not match the Name production"
}

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 Task={title:string;done:boolean};
const tasks:Task[]=[{title:"Read source",done:false},{title:"Test output",done:true}];
const list=document.createElement("ul");
tasks.forEach(task=>{const item=document.createElement("li");item.textContent=task.title;list.append(item);});
document.body.append(list);
__capture(list.children.length);
async function verifyContract():Promise<void>{await new Promise<void>(resolve=>setTimeout(resolve,15));const expected:string[]=["2"];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

const output=document.createElement("output");output.setAttribute("aria-live","polite");
output.textContent="Ready for review";document.body.append(output);
console.log(output.textContent);

Exact authored reference result

{
  "diagnostics": [],
  "logs": [
    "Ready for review"
  ],
  "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 2. 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 done:false to done:"false". Determine whether the contract, caller or business operation is wrong.

Hint 3

Restore done:false 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