Zero-background preparation
Read TypeScript for the First Time
No syntax dictionary. Build a tiny CodePilot task list by running, predicting, editing, and reading diagnostics.
How do TypeScript, JavaScript, Node.js, and browsers fit together?
Think of JavaScript as a recipe. A browser and Node.js are two kitchens that can follow it: browsers are good at web pages, while Node.js is good at files and servers.
TypeScript is a proofreader beside you while you write. It spots suspicious values before the program runs. The type notes are removed afterward, and the browser or Node.js receives ordinary JavaScript. Predict the output, run it, then change message to 42 and read the warning.
const message = "CodePilot ready";
console.log(message.toUpperCase());Playground 1 · Add a type to a task object
Predict whether the title or undefined will print. Then describe the task fields and let the editor catch titel.
运行后显示诊断。
等待执行。
Need a hint?
Create ReviewTask with a string title, number priority, and optional assignee.
Expected diagnostics: First task is implicitly any. After adding ReviewTask, the editor reports that titel does not exist and suggests title.
Expected output: Before: [1] undefined; after: [1] Check login
Show solution
type ReviewTask = {
title: string;
priority: number;
assignee?: string;
};
function formatTask(task: ReviewTask): string {
return `[${task.priority}] ${task.title}`;
}
console.log(formatTask({ title: "Check login", priority: 1 }));Meet the five values you will see most often
Programs spend most of their time storing and changing data. "CodePilot" is text, 1 is a number, and true is a yes/no value. null usually means “deliberately empty”; undefined usually means “not provided yet.”
const means the name will not be assigned a different value; let means it may change. Predict the five outputs, run the code, then replace count += 1 with count = "two" and read the diagnostic.
const project = "CodePilot";
let count = 1;
const enabled = true;
const owner: string | null = null;
let note: string | undefined;
count += 1;
console.log(project, count, enabled, owner, note);Playground 2 · Model task status with a union
Predict blocked and typo, then replace any string with four allowed states.
运行后显示诊断。
等待执行。
Need a hint?
Use todo | reviewing | done | blocked—like a menu with four choices.
Expected diagnostics: string accepts typo; the literal union rejects it.
Expected output: Blocked; the invalid typo call is removed.
Show solution
type TaskStatus = "todo" | "reviewing" | "done" | "blocked";
function statusLabel(status: TaskStatus): string {
if (status === "done") return "Done";
if (status === "reviewing") return "Reviewing";
if (status === "blocked") return "Blocked";
return "To do";
}
console.log(statusLabel("blocked"));An object is a task card; an array is a stack of cards
A review task has a title, tags, and perhaps an assignee. An object groups those related fields; an array stores a list of items. task.title reads the title field.
The ? after assignee means the field may be missing. The ?. only continues when an assignee exists. Predict the output, remove ?., and inspect the warning. Then complete the first Playground.
type ReviewTask = { title: string; tags: string[]; assignee?: string };
const task: ReviewTask = { title: "检查边界", tags: ["security"] };
console.log(task.title, task["tags"][0]);
console.log(task.assignee?.toUpperCase() ?? "未分配");Playground 3 · Read unknown input safely
Treat value as an unopened package. Prove it is an object with a string title before reading it.
运行后显示诊断。
等待执行。
Need a hint?
Check object, non-null, title in value, then string.
Expected diagnostics: value is unknown, so value.title cannot be read yet.
Expected output: SECURITY REVIEW
Show solution
function readTitle(value: unknown): string {
if (
typeof value === "object" &&
value !== null &&
"title" in value &&
typeof value.title === "string"
) {
return value.title.toUpperCase();
}
return "UNTITLED";
}
console.log(readTitle({ title: "security review" }));A function is a small machine with an input and an output
Put a title into format and it returns uppercase text. title: string says the input must be text; the : string after the parentheses says the output is text too. An arrow function is simply a shorter function syntax.
renderAll also receives a function to call later—a callback. Predict the array, then change format's output type to number. Read the error as: what did I provide, and what was required?
const format = (title: string): string => title.toUpperCase();
function renderAll(items: string[], render: (item: string) => string): string[] {
return items.map(render);
}
console.log(renderAll(["types", "runtime"], format));Not every string is a valid status
The editor can infer that inferred is a string from its value. You do not need to label every local variable; add annotations where the rule is not obvious.
The | symbol means “one of these choices.” Priority allows only 1, 2, or 3. A task status should allow todo, reviewing, done, or blocked—not any typo. The second Playground makes that difference visible.
let inferred = "review";
type Priority = 1 | 2 | 3;
type Result = string | null;
const priority: Priority = 1;
const result: Result = priority === 1 ? "urgent" : null;
console.log(inferred, result);You do not need to choose between type and interface yet
Long rules are easier to read when named. type TaskStatus names a set of choices. interface ReviewResult lists the fields a result must contain. extends adds fields to an existing object shape.
A useful beginner rule: use type for a fixed list of choices and interface for an object form. Run the code, remove summary, and see how the editor reports the missing field.
type TaskStatus = "todo" | "done";
interface ReviewResult { summary: string; status: TaskStatus }
interface DetailedResult extends ReviewResult { findings: number }
const result: DetailedResult = { summary: "通过", status: "done", findings: 0 };
console.log(`${result.summary}: ${result.findings}`);If you do not know what a value is, do not pretend
Network responses, user input, and JSON files are unopened packages. any closes your eyes and disables useful checking. unknown honestly says “I do not know yet,” so you must inspect the package first.
Use unknown at boundaries. In the third Playground, do not erase the warning with any. Use typeof and property checks to prove that title really is a string.
const unsafe: any = 42;
// unsafe.toUpperCase() 会通过类型检查,却在运行时失败
const input: unknown = { title: "review" };
console.log(typeof input);Type labels are gone when the program runs
Remember the proofreader? After checking, ReviewTask and : string are removed, leaving JavaScript. Types catch source-code mistakes, but they cannot inspect a real network response for you.
You can now read the basic code used later: M00 asks how to judge AI code, M01 explains how JavaScript behaves, and M02 handles work that finishes later.
type ReviewTask = { title: string };
function titleOf(task: ReviewTask): string { return task.title; }
console.log(titleOf({ title: "检查类型擦除" }));Finish with evidence, not a feeling
After the Playground, run this check from the project root. It never contacts a model.
npm run verify:lesson -- P00