Vibe coding with Claude Code course ยท Module 2: A Next.js project with Claude Code
TypeScript: types as a check on Claude
In this lesson16
Ahoy! Kraken's Call already has a hero section. Now you will meet the tool that checks Claude's code before a single player sees it: TypeScript and its compiler.
Problem: Claude writes with confidence, and the player sees the bug
Claude writes fast and with confidence, but sometimes it will enter a pirate's level as the text "5" instead of the number 5, or reach for a field the object does not have. In plain JavaScript such a bug shows up only in the browser, in front of the player. TypeScript catches it earlier, during a check that Claude can run itself before it reports "done". You do not write the types by hand: you should be able to read them and insist that the check passes honestly.
TypeScript in one paragraph
TypeScript is JavaScript with a type system. A type says what value may go in a given place: text, a number or an object with specific fields. Files .ts and .tsx are compiled to plain JavaScript, so the browser does not see the types. Here is a function that expects text:
function greet(name: string) {
return "Ahoy, " + name;
}
greet(5);The notation name: string says the parameter must be text, so for greet(5) the compiler reports an error before the code even starts. What types will not do: they disappear after compilation, so they will not check data the page receives while running, for example from the internet.
The check: the compiler as the bosun
tsc is the TypeScript compiler. In a Next.js project it mainly serves to check the types of the whole project with one command:
npx tsc --noEmitnpx from lesson 1_1 runs the tsc installed in the project, and --noEmit means: only check, do not write JavaScript files. When the types agree, the command prints nothing, so silence is a good sign. The Next.js documentation recommends it for checking types before a build.
You know the second check from lesson 1_2: npm run build also checks types (the "Running TypeScript" line) and stops on an error. A trap: Next.js generates the LayoutProps type used in app/layout.tsx only during npm run dev or npm run build, so in a freshly downloaded project tsc reports "Cannot find name 'LayoutProps'" until you build once. The captain's advice: ask for both checks, a quick tsc between steps and a build at the end.
Basic types
The simplest types are string (text), number (a number) and boolean (true or false). The type is written after a colon, right behind the variable name:
const shipName: string = "Black Pearl";
const crewCount: number = 3;
const isSailing: boolean = true;
const ports: string[] = ["Tortuga", "Nassau"];The last line is an array: string[] means "a list of texts". In Claude's code the type is often not written, because TypeScript infers it from the value: after let crewSize = 3, an attempt to put text there also ends in an error.
Interface: a contract for the shape of an object
The "Crew" section of the future landing page will show pirate cards. Each pirate is an object with several fields, and an interface is a contract that says what fields such an object must have and what type they are:
interface CrewMember {
name: string;
role: string;
level: number;
}From now on every object described as CrewMember must have a name and a role as text and a level as a number. An interface does not display or create anything: it is a shape the compiler guards.
An optional field and a union
Not every pirate has a parrot, so that field will be optional: a question mark after the name marks it. A role, in turn, should not be any text, only one of a few known ones. A union (union type) serves this: a type made of several possibilities joined with the | sign, which you read as "or":
type CrewRole = "captain" | "helmsman" | "cook" | "bosun";
interface CrewMember {
name: string;
role: CrewRole;
level: number;
parrot?: string;
}The word type gives a name to any type, here a union of four strings. The role "captain" passes, but "captan" with a typo does not: the compiler answers "Type '"captan"' is not assignable to type 'CrewRole'" and even suggests the correct value. The field parrot? may be left out, but the code must check whether the parrot exists before it uses it.
type or interface?
Both forms describe the shape of an object and are usually interchangeable, but a union can be written only with type. The TypeScript documentation advises: use interface until you need something only type gives. I stick to that but when Claude describes an object with type, do not make it change that: it is not a mistake.
Request for Claude Code
Time for Claude to build the crew page with types and check it itself. In the session in the krakens-call folder, still in Manual mode, give this request:
Request for Claude Code:
Add a page app/crew/page.tsx with a "Crew" section for Kraken's Call:
three pirate cards (name, role, level, optionally the parrot's name).
In this file define an interface CrewMember, the role as a union of
several strings and a CrewCard component with typed props. No any, no
as, no @ts-ignore and no changes to tsconfig.json and next.config.ts.
Tailwind classes in the style of @app/page.tsx. At the end run
npx tsc --noEmit and npm run build and show both results.The bans in the fourth sentence close the shortcuts we will get to in a moment, and the last sentence demands proof: two results instead of the word "done".
What Claude wrote
Open app/crew/page.tsx in Cursor. At the top stand the already familiar CrewRole and CrewMember, and below them the crew data:
const crew: CrewMember[] = [
{ name: "Anne Bonny", role: "captain", level: 10, parrot: "Captain Feather" },
{ name: "Jack Rackham", role: "helmsman", level: 7 },
{ name: "Mary Read", role: "cook", level: 5 },
];CrewMember[] is an array of objects that follow the contract. Only the first pirate has a parrot, because the field is optional. The data is written in the file: the page fetches nothing from the internet.
Next the component of one card. Props are the data a component receives from its parent, much like a function receives arguments, and their shape is also described by an interface:
interface CrewCardProps {
member: CrewMember;
}
function CrewCard({ member }: CrewCardProps) {
return (
<article className="rounded-lg border border-yellow-500 bg-gray-900 p-6 text-white">
<h3 className="text-xl font-bold">{member.name}</h3>
<p className="mt-2 text-gray-300">
{member.role}, level {member.level}
</p>
{member.parrot && (
<p className="mt-2 text-yellow-400">Parrot: {member.parrot}</p>
)}
</article>
);
}{ member }: CrewCardProps says the card takes one prop member of type CrewMember. The notation member.parrot && (...) shows the parrot paragraph only when the field exists: that is what checking an optional field looks like. Had Claude written member.ship, the compiler would report that the contract has no such field.
At the end of the file, the page that lays the cards out in a grid:
export default function CrewPage() {
return (
<main className="min-h-screen bg-black px-6 py-16">
<h1 className="text-center text-3xl font-bold text-red-600">Crew</h1>
<div className="mx-auto mt-8 grid max-w-4xl grid-cols-1 gap-4 md:grid-cols-3">
{crew.map((member) => (
<CrewCard key={member.name} member={member} />
))}
</div>
</main>
);
}crew.map creates a card for each pirate, and key gives React a unique label for a list element. You know the grid from lesson 1_3. The file lies in the app/crew/ folder, so the page will be at the address /crew.
Proof: two results
Claude will show the result of both commands. After npx tsc --noEmit there is no text at all, and the build ends like this:
โ Compiled successfully in 1523ms
Running TypeScript ...
Finished TypeScript in 745ms ...
Route (app)
โ โ /
โ โ /_not-found
โ โ /crewThe /crew line confirms that the page exists, and the TypeScript lines that the types agree. Also open http://localhost:3000/crew: a build checks the code, but it will not judge the legibility of the cards for you.
What a type error looks like
See what would happen if Claude entered Mary Read's level as the text "5". npx tsc --noEmit would print one line:
app/crew/page.tsx(13,41): error TS2322: Type 'string' is not assignable to type 'number'.You read from the left: the file, the line and column, the error code and the description: the level field holds text, and the contract requires a number. npm run build will print the same message and finish with the words "Failed to type check.", so the broken version will not be built.
You will see the same error in Cursor without any commands. Cursor is built on VS Code code, so what the VS Code documentation describes for TypeScript works in it: errors are marked in the text of the file, and when you hover over a name you see its type, for example CrewMember at member. The Problems panel shows the list of errors (Cmd+Shift+M on a Mac, Ctrl+Shift+M on Windows and Linux).
A typical agent mistake: silencing instead of fixing
When the check does not pass, an agent can be tempted to silence it instead of fixing the cause. The check then passes because it stopped looking. You will recognise four tricks:
as any:asis a type assertion, that is "I know better", andanyturns checking off;// @ts-ignoreor// @ts-expect-errorabove the line with the error: the compiler skips that line;"strict": falseintsconfig.json: the strict checks disappear, for example the warning "'captain' is possibly 'undefined'" that the pirate you look for may not exist;ignoreBuildErrors: trueinnext.config.ts: the build does not check types at all, which the Next.js documentation openly calls dangerous.
This is how the first trick looks in the diff in Source Control:
- { name: "Mary Read", role: "cook", level: "5" },
+ { name: "Mary Read", role: "cook", level: "5" as any },The real fix would change "5" to 5, and this one leaves text where the contract requires a number. The assertion disappears after compilation like every type, so it fixes nothing: the error only hid from the compiler.
How to catch it: in the diff look for any, as and @ts-, and in Source Control check that tsconfig.json and next.config.ts have not changed. The linter helps too: in a project from create-next-app the command npm run lint reports as any as the error "Unexpected any" and rejects @ts-ignore. When you find such a trick, answer:
Remove as any from app/crew/page.tsx and fix the cause: level must be
a number matching CrewMember. Do not change tsconfig.json. Then run
npx tsc --noEmit and npm run lint and show both results.The answer names the cause, closes the shortcut and again demands proof.
What you will meet in Claude's code
You do not have to write these forms: it is enough that you recognise them in Claude's code.
Generics are types with a parameter in angle brackets: Array<CrewMember> means the same as CrewMember[]. This is how, for example, a server response with variable content is described:
interface ApiResponse<T> {
data: T;
status: number;
}
const answer: ApiResponse<CrewMember[]> = { data: crew, status: 200 };T is a place for a type that you give when you use it, here a list of pirates. The Api prefix is deliberate: Response in a file with no imports and exports collides with the browser's built-in type, and tsc reports "All declarations of 'Response' must have identical type parameters".
Utility types build a new type from an existing one. Partial makes all fields optional, Pick chooses a few of them, and Omit leaves a few out:
type CrewDraft = Partial<CrewMember>;
type CrewBadge = Pick<CrewMember, "name" | "role">;
type CrewWithoutParrot = Omit<CrewMember, "parrot">;CrewBadge has only the name and the role, just right for a small badge, and Required works the opposite of Partial. None of these forms changes CrewMember itself: new names appear next to it.
unknown instead of any. Both types accept any value, but unknown will not let you use it until you check what it is:
function shout(value: unknown) {
if (typeof value === "string") {
return value.toUpperCase();
}
return "???";
}Inside the if TypeScript already knows that value is text, so toUpperCase() is allowed, whereas with any it would let a call of any method through. More rarely you will see never, the type of a value that never arises, for example the result of a function that always throws an error.
tsconfig.json: compiler settings
The TypeScript settings lie in the tsconfig.json file that the wizard created. The most important line for you is this one:
"strict": true,strict turns on a whole family of strict checks, among others noImplicitAny, which reports places where a type would quietly become any, and strictNullChecks, which guards the values null and undefined. Every proposal to change this line is a signal to stop Claude.
Captain's review
Before you approve the crew page, check:
- An honest check: the diff has no
any,asor@ts-, and the list of changes does not includetsconfig.jsonornext.config.ts. - Proof, not a report: you saw the empty result of
npx tsc --noEmitand the build table with/crew. - Types describe the data:
CrewMemberhas the fields that are visible on the cards, with none invented in advance. - The page: at
/crewthere are three cards, and on a narrow screen one under another.
You already know the typical agent mistake: silencing a type error instead of fixing it. You will catch it most surely when you add a third check, npm run lint, to the two checks from the request.
Next step
Hold off on the commit: in the next lesson you will make it after reviewing the changes and send the project to GitHub. In the editor below stands the same crew page with types: add a bosun with a parrot and see him in the preview.
Remember: types are a map with the shoals marked, and the compiler is the bosun who checks the course before the ship sails.
Code for this lesson: App.tsx
// Kraken's Call - crew page described with TypeScript types
type CrewRole = "captain" | "helmsman" | "cook" | "bosun";
interface CrewMember {
name: string;
role: CrewRole;
level: number;
parrot?: string; // optional field: not every pirate has a parrot
}
interface CrewCardProps {
member: CrewMember;
}
const crew: CrewMember[] = [
{ name: "Anne Bonny", role: "captain", level: 10, parrot: "Captain Feather" },
{ name: "Jack Rackham", role: "helmsman", level: 7 },
{ name: "Mary Read", role: "cook", level: 5 },
// Try it: add a bosun with a parrot, for example { name: "Israel Hands", role: "bosun", level: 6, parrot: "Squall" }
];
function CrewCard({ member }: CrewCardProps) {
return (
<article style={{ background: "#111827", color: "white", padding: 16, borderRadius: 8, border: "1px solid #eab308" }}>
<h3 style={{ margin: "0 0 8px" }}>{member.name}</h3>
<p style={{ margin: 0, color: "#d1d5db" }}>
{member.role}, level {member.level}
</p>
{member.parrot && (
<p style={{ margin: "8px 0 0", color: "#facc15" }}>Parrot: {member.parrot}</p>
)}
</article>
);
}
export default function App() {
return (
<main style={{ minHeight: "100vh", background: "black", padding: 32, fontFamily: "system-ui, sans-serif" }}>
<h1 style={{ color: "#dc2626", textAlign: "center", marginTop: 0 }}>Crew</h1>
<div style={{ display: "grid", gap: 16, gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))" }}>
{crew.map((member) => (
<CrewCard key={member.name} member={member} />
))}
</div>
</main>
);
}Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is TypeScript?
2. What is an interface used for in TypeScript?
3. Claude fixed a type error by adding as any, and npx tsc --noEmit passes. What do you do?
Hands-on tasks in the game
- Horizontal ordering
Arrange a typed string variable declaration in TypeScript (left to right):
- Click in order
Build an optional 'parrot' field of type string in the CrewMember interface: