TypeScript Foundations
Types, unions, narrowing, functions, objects, collections, runtime checks, discriminated unions, generics and local modules. Introductory static and runtime coverage only.
Audience: Learners familiar with the Web Foundations JavaScript examples.
Practice: 4 to 6 hours.
Runtime and boundaries: Compiler: /usr/local/lib/node_modules/openclaw/node_modules/typescript/lib/tsc.js (6.0.3), invoked with installed Node 24.18.0. It is bundled with an existing package and is not on PATH. No package manager was run. Use the supplied tsconfig.json and package.json in a fresh practice directory, with one entry example and any companion. Check with node followed by the quoted compiler path and --project . --noEmit; emit with the same command without --noEmit; run the emitted .js with node. The browser exports source text only. See README for exact commands and limits.
Lessons
Types and execution
TypeScript checks source before execution. Node runs the emitted JavaScript separately. Passing one stage does not prove the other; annotations are erased and do not validate incoming JSON. These examples use TypeScript 6.0.3 and Node 24.18.0, not Node type stripping.
A reproducible compiler contract
The included tsconfig enables strict, noUncheckedIndexedAccess and exactOptionalPropertyTypes, with ES2020 and Node16 module resolution. types: [] prevents ambient packages from changing the exercise. DOM declarations are included here for console typing; they also declare browser APIs that Node does not supply. Use the installed compiler path recorded in the toolchain evidence.
Values, functions and collections
Start with inference and annotate public contracts where useful. Unions describe alternatives. readonly parameters restrict mutations through that reference. Empty arrays and missing keys need explicit outcomes; defaults should preserve zero and false.
Objects and absence
An optional property can be absent. The exact optional flag distinguishes absence from explicitly writing undefined unless undefined is part of its declared type. readonly is a static restriction rather than a runtime freeze or an ownership system.
Narrowing and runtime validation
Use typeof, null checks and discriminators to narrow unions. unknown requires a check before use; any bypasses useful checks. JSON.parse can return anything and a cast only changes what the compiler believes. Bound inputs before parsing, then validate the application contract.
Errors and exhaustiveness
An error diagnostic is a static result, while a thrown Error is a runtime event. catch values are unknown under strict checking. A never assignment can reveal a missing branch in a discriminated union. noEmitOnError must be enabled to prevent output after compiler errors.
Generics and local modules
Generics preserve relationships between types rather than providing runtime introspection. A local module exports a value and imports it by a path. Module settings, filename suffixes and package.json determine emitted behavior; this pack deliberately fixes one CommonJS configuration.
Practice and limits
Run each example in its own folder with its companions and the supplied config. First check with --noEmit, then emit only after checks pass and run the corresponding .js file. Expected failures are kept in source JSON and the test evidence. No JSX, frameworks, package installation, deployment, advanced type metaprogramming or cross-platform claim is included.
Reference cards
Values: const count: number = 2
Annotation or inference constrains assignments.
Union: string | number
Check the active case before case-specific methods.
Function: (x: number): number
Types describe parameter and return contracts.
Collection: readonly number[]
Restricts writes through this reference.
Optional: minutes?: number
May be absent; explicit undefined depends on flags/type.
Default: value ?? fallback
Uses fallback only for null or undefined.
Index: Record<string, number>
Unknown keys need checking with the chosen flags.
Unknown: value: unknown
Requires narrowing before use.
Guard: typeof value === "string"
Runtime test that narrows a static type.
Discriminator: kind: "ok" | "error"
Literal tags can identify object variants.
Exhaustiveness: const impossible: never = value
Unhandled cases become type errors.
Generic: function first<T>(xs: T[])
Relates input and output types.
Module: import {x} from "./module.js"
Resolves .ts source and names emitted .js output here.
Static check: node <compiler> --project . --noEmit
Checks only; no JavaScript execution.
Emit: noEmitOnError: true
Suppresses output on compiler diagnostics.
Run: node "Example.js"
Executes emitted code; does not perform typechecking.
Supporting configuration: tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "Node16",
"moduleResolution": "Node16",
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noEmitOnError": true,
"types": [],
"lib": [
"ES2020",
"DOM"
]
},
"include": [
"*.ts"
]
}
Supporting configuration: package.json
{"type":"commonjs"}
Examples and practice
Code below is reading material, not an execution console. Download the edition for the complete example files and companion modules.
TypeScript 01 - Values and inference
Annotations constrain assignments; inference also records a type. typeof here is a JavaScript runtime operation. Type annotations disappear from emitted JavaScript.
const learnerName: string = "Ada";
const minutes = 25;
const ready: boolean = minutes > 0;
console.log(`${learnerName}: ${minutes} minutes`);
console.log(ready, typeof minutes);
Expected:
Ada: 25 minutes true number
Intentionally invalid TypeScript: expected compiler diagnostic TS2322. Rejected static check, not a successful program or runtime output.
const minutes: number = "25";
TypeScript 02 - Narrow a union
A typeof guard narrows each branch. No assertion or any is needed.
function label(value: string | number): string {
return typeof value === "string"
? value.trim().toUpperCase() : value.toFixed(1);
}
console.log(label(" notes "));
console.log(label(2.5));
Expected:
NOTES 2.5
Intentionally invalid TypeScript: expected compiler diagnostic TS2339. Rejected static check, not a successful program or runtime output.
function f(x: string | number) { return x.toUpperCase(); }TypeScript 03 - Function contracts
readonly describes this function parameter; it is not a deep runtime freeze. The initial accumulator handles an empty list.
function total(values: readonly number[], bonus = 0): number {
return values.reduce((sum, value) => sum + value, bonus);
}
console.log(total([10, 20], 5));
console.log(total([]));
Expected:
35 0
Intentionally invalid TypeScript: expected compiler diagnostic TS2345. Rejected static check, not a successful program or runtime output.
function total(x: number): number { return x; }
total("5");TypeScript 04 - Optional object fields
With exactOptionalPropertyTypes, an absent minutes field differs from explicitly supplying undefined. readonly checks assignment through this type, not mutation by all possible aliases.
type Note = { readonly title: string; minutes?: number };
function describe(note: Note): string {
return `${note.title}: ${note.minutes ?? 0}`;
}
console.log(describe({title: "Read"}));
console.log(describe({title: "Practice", minutes: 20}));
Expected:
Read: 0 Practice: 20
Intentionally invalid TypeScript: expected compiler diagnostic TS2375. Rejected static check, not a successful program or runtime output.
type N = { minutes?: number };
const n: N = { minutes: undefined };Intentionally invalid TypeScript: expected compiler diagnostic TS2540. Rejected static check, not a successful program or runtime output.
const n: {readonly title: string} = {title: "A"};
n.title = "B";TypeScript 05 - Missing indexed values
noUncheckedIndexedAccess makes uncertain index results include undefined. Nullish defaults preserve legitimate zero values.
const minutes: Record<string, number> = {read: 20};
const first: number[] = [];
console.log(minutes["read"] ?? 0);
console.log(minutes["missing"] ?? 0);
console.log(first[0] ?? "empty");
Expected:
20 0 empty
Intentionally invalid TypeScript: expected compiler diagnostic TS2322. Rejected static check, not a successful program or runtime output.
const xs: number[] = []; const x: number = xs[0];
TypeScript 06 - Check runtime data
Assign untrusted-shaped values to unknown and check the runtime contract. This toy accepts extra keys and fractional nonnegative minutes; it is not JSON Schema validation. Type assertions would not validate input.
function minutes(value: unknown): number {
if (typeof value !== "object" || value === null ||
!("minutes" in value) ||
typeof value.minutes !== "number" ||
!Number.isFinite(value.minutes) || value.minutes < 0) {
throw new Error("invalid minutes");
}
return value.minutes;
}
const raw: unknown = JSON.parse('{"minutes":15}');
console.log(minutes(raw));
try { minutes({minutes: "15"}); }
catch (error) {
console.log(error instanceof Error ? error.message : "error");
}
Expected:
15 invalid minutes
Intentionally invalid TypeScript: expected compiler diagnostic TS18046. Rejected static check, not a successful program or runtime output.
const value: unknown = 1; value.toFixed();
TypeScript 07 - Discriminated results
A literal discriminator narrows the object. The never assignment makes a newly added, unhandled variant a compile-time error.
type Result = {kind: "ok"; value: number} |
{kind: "error"; message: string};
function show(result: Result): string {
switch (result.kind) {
case "ok": return `Value: ${result.value}`;
case "error": return `Error: ${result.message}`;
default: {
const impossible: never = result;
return impossible;
}
}
}
console.log(show({kind: "ok", value: 3}));
console.log(show({kind: "error", message: "missing"}));
Expected:
Value: 3 Error: missing
Intentionally invalid TypeScript: expected compiler diagnostic TS2322. Rejected static check, not a successful program or runtime output.
type R = {kind:"ok"} | {kind:"wait"};
function f(r:R) { if(r.kind==="ok") return;
const impossible: never = r; }TypeScript 08 - Preserve a type relationship
The generic relates the input element type to the output. It does not invent a value when the collection is empty.
function first<T>(items: readonly T[]): T | undefined {
return items[0];
}
console.log(first(["alpha", "beta"]) ?? "empty");
console.log(first<number>([]) ?? "empty");
Expected:
alpha empty
Intentionally invalid TypeScript: expected compiler diagnostic TS2322. Rejected static check, not a successful program or runtime output.
function first<T>(xs:T[]):T|undefined {return xs[0];}
const n: number = first(["one"]);TypeScript 09 - A local module
Keep the companion beside the entry file. The .js import matches the emitted file; Node16 resolution finds its .ts source for checking. The supplied package.json selects CommonJS output; no package download is involved.
import { double } from "./Atlas math.js";
console.log(double(6));
Expected:
12
Companion file: Atlas math.ts
export function double(value: number): number {
return value * 2;
}
TypeScript exercise A - A safe average
A union return type forces the caller to account for an empty input. The finite-number requirement remains the caller contract.
function average(values: readonly number[]): number | undefined {
if (values.length === 0) return undefined;
return values.reduce((sum, n) => sum + n, 0) / values.length;
}
console.log(average([10, 20]) ?? "empty");
console.log(average([]) ?? "empty");
Expected:
15 empty
Practice: Write average for a finite-number array. Return undefined for an empty array and display a useful fallback.
TypeScript exercise B - Validate a label
Validation is runtime code and survives compilation. It checks type and nonblank content, not a universal naming policy.
function label(value: unknown): string {
if (typeof value !== "string" || value.trim().length === 0) {
throw new Error("label required");
}
return value.trim();
}
for (const value of [" Practice ", " ", 7]) {
try { console.log(label(value)); }
catch (error) {
console.log(error instanceof Error ? error.message : "error");
}
}
Expected:
Practice label required label required
Practice: Accept unknown, return a trimmed nonblank string, and reject whitespace-only or non-string inputs.
TypeScript exercise C - Summarize a tagged task
The shared discriminator gives access to minutes only in the done branch.
type Task = {state: "open"; title: string} |
{state: "done"; title: string; minutes: number};
function summary(task: Task): string {
return task.state === "done"
? `${task.title}: ${task.minutes} minutes`
: `${task.title}: open`;
}
console.log(summary({state: "open", title: "Read"}));
console.log(summary({state: "done", title: "Code", minutes: 30}));
Expected:
Read: open Code: 30 minutes
Practice: Use a union so an open task cannot require minutes. Display both states without any or type assertions.
Prompt templates
These are editable planning prompts in the downloadable workbench; they do not contact an AI service here.
Build a small example
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Return complete runnable files, expected output and a minimal verification procedure. Keep compile diagnostics, JavaScript output and runtime observations separate.Diagnose a failure
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Use the exact diagnostic or traceback. Explain one cause, one minimal correction and a regression check. Keep compile diagnostics, JavaScript output and runtime observations separate.Design boundary tests
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Include valid, invalid, empty and missing values. Distinguish proposed tests from executed evidence. Keep compile diagnostics, JavaScript output and runtime observations separate.Refactor with preserved behavior
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Show the before/after contract, preserve observed outputs and list changed assumptions. Keep compile diagnostics, JavaScript output and runtime observations separate.Document a contract
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Explain inputs, outputs, errors, encoding and environmental requirements, including unsupported cases. Keep compile diagnostics, JavaScript output and runtime observations separate.Review trust boundaries
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Inspect parsing, type assumptions and resource bounds. Explain what the checks do not guarantee. Keep compile diagnostics, JavaScript output and runtime observations separate.Further reading
- TypeScript: The basics — Static checks, erased types and JavaScript output.
- TypeScript: Everyday types — Primitive, union and object types.
- TypeScript: Narrowing — Guards, discriminators and never.
- TypeScript: Functions — Function signatures and unknown.
- TypeScript: Object types — Optional and readonly fields.
- TypeScript: Generics — Relationships between types.
- TypeScript: strict — Strict checking group.
- TypeScript: noEmitOnError — Suppress output on errors.
- TypeScript: noUncheckedIndexedAccess — Unchecked indices include undefined.
- TypeScript: exactOptionalPropertyTypes — Absent versus undefined fields.
- TypeScript: Module reference — Node16 and extension resolution.
Download the offline edition
Complete Atlas 0.11.0 ZIP (6,079,970 bytes) · 411-page guide and catalogue PDF · Versioned source JSON
Unzip the edition and open Programming and Scripting Atlas.html, Web Foundations.html, Python Foundations.html, SQL Foundations.html, Shell Foundations.html, TypeScript Foundations.html Data Formats Foundations.html, C Foundations.html C++ Foundations.html, Ruby Foundations.html, Perl Foundations.html, Swift Foundations.html, Makefile Foundations.html, awk Foundations.html, sed Foundations.html, jq Foundations.html, XSLT 1.0 Foundations.html, Tcl Foundations.html, Expect Foundations.html or Objective-C Foundations.html locally. The original interactive workbenches retain their offline prompt-building, local presets and export controls. Read the included README before running examples yourself. The workbench does not execute pasted code or call an AI service; prompt text is for you to inspect and use separately.
Version 0.11.0 is pinned here. The other 257 registry entries remain planned; this edition does not claim complete language coverage.
Evidence and limits
Objective-C adds 12 accepted native programs, four separate compiler or warning-policy rejections, 120 root checks and 147 independent native checks. Two rejection fixtures are warnings promoted by -Werror; they are not intrinsic syntax failures. No rejected fixture was executed. Tests dated 26 October 2026 used Apple Clang 21.0.0, ARC, C17 base mode, macOS SDK 27.0 headers and system Foundation 6.9 (5027.0.69) on macOS 27.0.1 arm64. This is introductory macOS/Foundation coverage, not iOS, GNUstep, Objective-C++, UI, concurrency or cross-platform coverage. No sanitizers, leak detector, race analysis, allocation/disk-full/permission fault injection or asynchronous timing tests were run. Trusted authored fixtures and process bounds do not establish an arbitrary-code sandbox.
The pinned Atlas 0.11.0 evidence records 607 browser checks, 55 Python harness checks plus four unittest methods, 74 SQL checks, 515 shell checks across 71 runs, 99 TypeScript checks, 51 Data Formats checks, 119 C checks, 116 C++ checks, 97 Ruby checks, 97 Perl checks, 105 Swift harness checks and 97 Makefile harness checks, 145 awk checks, 145 sed checks, 161 jq checks, 157 XSLT checks, 150 Tcl checks and 161 Expect checks. These are separate measures. Tcl and Expect tests are dated 26 October 2026 on installed Tcl 8.5.9 / Expect 5.45 with Tcl 8.5.9 on macOS arm64. These old versions are recorded teaching evidence, not deployment recommendations. Tcl has 12 accepted programs and Expect has 12 accepted controllers; each has four expected evaluation failures, not static compilation passes. Tcl has nine scenarios, five expected nonzero; Expect has seven scenarios, four expected nonzero. Expect default controllers invoke 15 toy children, including two expected child failures; one scenario also expects a failed child. Controller success does not mean every child succeeds. The authoring release records 100 owned-runner regression checks and 109 independent runner checks separately. Only authored fixtures and retained native child handles are covered. Cooperative cleanup requires event-loop progress; outer-timeout child cleanup remains uncertain without complete wait receipts. The retired PID-inspection branch was not retried. No sign-ins, secrets, network or external application control are taught or tested by this pack. awk and sed are text-processing languages; their examples use fixed authored ASCII input and the C locale with installed awk 20200816 and macOS sed on one platform. jq and XSLT each have 12 accepted examples and four separately rejected programs. jq has 21 scenarios, including five contract errors and one no-result status; XSLT has 20 scenarios, including five terminating messages and one CLI parameter rejection. Expected nonzero outcomes are not successful programs. Tests dated 26 October 2026 used jq 1.7.1-apple and XSLT 1.0 with libxslt 1.1.35/libxml2 2.9.13, fixed trusted programs and tiny authored inputs in the C locale on macOS arm64. These old installed XML libraries are recorded learning environments, not recommendations for untrusted-document processing. No imports, external documents, DTDs, custom/external entities, extension functions or generated source are covered. Command flags and bounds are not a complete sandbox. Standalone XPath remains planned; supporting XPath 1.0 expressions are limited to these XSLT examples. These tests do not establish GNU-tool equivalence, Unicode behavior, arbitrary-script safety or cross-platform portability. Swift has 12 accepted programs and four expected static rejections; Makefile has 12 accepted default targets, four expected parser rejections, eight additional scenarios and one expected recipe failure. Makefile is build scripting, not a general-purpose language. The Swift and Makefile test execution dates remain 25 October 2026. awk and sed tests are dated 26 October 2026. Delivery verification does not replace or refresh test execution dates. TypeScript includes 12 accepted programs executed as JavaScript and nine intentionally invalid cases correctly rejected. Each C/C++ pack has 12 accepted programs run normally and with AddressSanitizer/UndefinedBehaviorSanitizer, plus four expected compiler rejections that are never executed. Ruby and Perl each have 12 syntax-accepted programs executed and four expected syntax rejections; rejected cases are not successful programs. Syntax checks may execute compile-time code and are not arbitrary-code sandboxes. Sanitizer results cover executed paths only; leak detection and allocation-failure injection were not tested and memory safety is not proved.
Tested environments are Chrome 155, CPython 3.9.6, SQLite CLI 3.54.0, macOS sh/Bash 3.2.57/Zsh 5.9, TypeScript 6.0.3, Node 24.18.0 Apple Clang 21.0.0, Ruby 2.6.10p210 and Perl 5.34.1, Apple Swift 6.4 in Swift 6 mode and GNU Make 3.81 on one arm64 macOS host. C uses a C17 subset; C++ uses a C++20 subset with libc++ 220106. Python 3.9.6 is unsupported upstream. Ruby 2.6 is end-of-life upstream; the recorded installed interpreter is not a recommended modern runtime. Data Formats uses installed Tomli 1.0.3 through a private fallback; the Python tomllib branch was not run. No new-installation recommendation, complete language/format conformance, schema certification, hardened untrusted XML parsing or general-purpose execution sandbox is established. Other platforms, browsers and screen readers remain unverified. The 145 official references belong to the saved Atlas review, not fresh website-time verification.