Lab: Convert a JavaScript Module to Strict TypeScript
Convert a working search module from JavaScript to strict TypeScript: keep the behaviour, let the compiler find the latent bugs, and validate the API payload with a discriminated union.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: run the JavaScript as it is
- Step 2: type-check the JavaScript first
- Step 3: rename to .ts
- Step 4: model the data and annotate
- Step 5: validate the payload and finish main
- Step 6: prove the validator rejects bad data
- Step 7: make the check a habit
- Step 8: use a package that ships no types
- Check your understanding
- Apply it
- Review prompt
Lessons of TypeScript Foundations
- Why Types: Annotations, Inference and the Compiler Concept · 20 min
- Modeling Data with Unions, Literals and Interfaces Worked example · 25 min
- Narrowing and Validating Data You Do Not Control Worked example · 25 min
- Generics and Types Built from Other Types Concept · 25 min
- Lab: Convert a JavaScript Module to Strict TypeScript Lab · 30 min
- Check: Type Puzzles and Compiler Errors Knowledge check · 8 questions
What you will learn
- Annotate functions, objects and arrays where inference is not enough, and model domain data with type aliases, interfaces, literal types and unions.
- Narrow union and unknown values with typeof, in, equality checks, type predicates and discriminated unions, and validate untrusted runtime data such as API responses before relying on its type.
- Write generic functions and types, and derive types with keyof, typeof, indexed access and utility types such as Partial, Pick, Omit and Record.
- Configure a strict tsconfig, run type checks as part of the build, and consume typed third-party packages and declaration files.
Prerequisites: JavaScript Foundations
01. Goal and setup
This lab converts a real JavaScript module — the ranking core of the search feature from the async JavaScript lab — to strict TypeScript, keeping the behaviour unchanged at every step. The point is not retyping by hand: it is letting the compiler report what the JavaScript has always silently assumed, then deciding whether each assumption deserves a type, a guard or a runtime check.
You need: Node.js 22 or later and npm. The lab pins [email protected], the current release (the compiler rewritten in Go), and [email protected]; every message below was captured with these on Node 22.23. TypeScript 6.0 and later turn strict on by default; step 2 still sets it explicitly, so the config reads the same on any version. Everything stays in one folder:
mkdir search-ts && cd search-tsnpm init -ynpm pkg set type=module— the module uses ECMAScriptimport/exportnpm pkg set scripts.start="tsx src/main.ts"— one command to run itnpm install --save-dev [email protected] [email protected]
added 5 packages, and audited 6 packages in 10s
found 0 vulnerabilitiestsx runs TypeScript files directly, with no build step, which makes the feedback loop short. You will end with this layout:
search-ts/
├── package.json "type": "module", dependencies, scripts
├── tsconfig.json added in step 2
├── vendor/
│ └── slugify-lite/ step 8: a small package that ships no types
└── src/
├── search.ts the module (starts as search.js)
├── main.ts a small client of the module
├── check-parse.ts step 6: feeds bad payloads to the validator
├── links.ts step 8: imports the untyped package
└── types/
└── slugify-lite.d.ts step 8: the declaration you write02. Step 1: run the JavaScript as it is
Create the two files below. The module ranks notes against a query — exact match beats prefix, prefix beats substring — and hands back the top few. The client parses a JSON payload and prints the best match per query. This is ordinary, working JavaScript of the kind found in every frontend repo:
const MAX_RESULTS = 5;
const WEIGHTS = { exact: 3, prefix: 2, substring: 1 };
export function rank(notes, query) {
const q = query.trim().toLowerCase();
const scored = [];
for (const note of notes) {
const score = scoreNote(note.title, q);
if (score > 0) scored.push({ note, score });
}
scored.sort((a, b) => b.score - a.score);
return scored.slice(0, MAX_RESULTS);
}
function scoreNote(title, q) {
const t = title.toLowerCase();
if (t === q) return WEIGHTS.exact;
if (t.startsWith(q)) return WEIGHTS.prefix;
if (t.includes(q)) return WEIGHTS.substring;
return 0;
}
// Trust the server for now: whatever arrives, hand it on.
export function parseNotes(text) {
return JSON.parse(text);
}import { parseNotes, rank } from './search.js';
const payload = `[
{"id": "n1", "title": "Union types"},
{"id": "n2", "title": "Type narrowing"},
{"id": "n3", "title": "Utility types"}
]`;
const notes = parseNotes(payload);
for (const query of ['ty', 'union', 'zig']) {
const top = rank(notes, query)[0];
console.log(query, '->', top ? top.note.title : '(no match)');
}node src/main.jsty -> Type narrowing
union -> Union types
zig -> (no match)This output is the contract for the whole lab: the finished conversion must print exactly this. Note two fragile spots in the JavaScript. rank(notes, query)[0] reads the first element of a possibly empty result. And parseNotes hands whatever JSON.parse returns straight to the caller, so a renamed field fails in the UI, far from the parse.
03. Step 2: type-check the JavaScript first
You do not have to rename anything to get value from the compiler. Add a tsconfig.json with checkJs, and TypeScript will analyse your .js files in place — the gentlest possible entry, because every error it reports is a fact about code you already have:
{
"compilerOptions": {
"target": "es2022",
"module": "nodenext",
"moduleResolution": "nodenext",
"strict": true,
"noUncheckedIndexedAccess": true,
"allowJs": true,
"checkJs": true,
"noEmit": true
},
"include": ["src"]
}npx tsc --noEmitsrc/search.js(4,22): error TS7006: Parameter 'notes' implicitly has an 'any' type.
src/search.js(4,29): error TS7006: Parameter 'query' implicitly has an 'any' type.
src/search.js(15,20): error TS7006: Parameter 'title' implicitly has an 'any' type.
src/search.js(15,27): error TS7006: Parameter 'q' implicitly has an 'any' type.
src/search.js(24,28): error TS7006: Parameter 'text' implicitly has an 'any' type.Five errors, all the same species: under strict, the compiler refuses to pretend it knows what notes, query, title, q and text are. Nothing here is a bug yet; these are the unknowns a conversion must resolve. (The imports in main.js end in .js: with Node-style resolution you keep the runtime extension even after the files become TypeScript.)
04. Step 3: rename to .ts
Now make it official, and drop allowJs and checkJs from the tsconfig so only TypeScript files are checked:
mv src/search.js src/search.ts
mv src/main.js src/main.ts
npx tsc --noEmitsrc/search.ts(4,22): error TS7006: Parameter 'notes' implicitly has an 'any' type.
src/search.ts(4,29): error TS7006: Parameter 'query' implicitly has an 'any' type.
src/search.ts(15,20): error TS7006: Parameter 'title' implicitly has an 'any' type.
src/search.ts(15,27): error TS7006: Parameter 'q' implicitly has an 'any' type.
src/search.ts(24,28): error TS7006: Parameter 'text' implicitly has an 'any' type.The same five TS7006 errors, now in .ts files. A rename is free — valid JavaScript is, with small exceptions, valid TypeScript — which is why conversion happens in place rather than by rewriting. The five unknowns are the work list for the next two steps.
05. Step 4: model the data and annotate
Give the module its vocabulary. A note is a record with an id and a title; the weights are a fixed table, so as const turns the numbers into literal types; and the parameters get the annotations the compiler asked for in steps 2 and 3:
type Note = { id: string; title: string };
const MAX_RESULTS = 5;
const WEIGHTS = { exact: 3, prefix: 2, substring: 1 } as const;
export function rank(notes: Note[], query: string) {
const q = query.trim().toLowerCase();
const scored: { note: Note; score: number }[] = [];
for (const note of notes) {
const score = scoreNote(note.title, q);
if (score > 0) scored.push({ note, score });
}
scored.sort((a, b) => b.score - a.score);
return scored.slice(0, MAX_RESULTS);
}
function scoreNote(title: string, q: string): number {
const t = title.toLowerCase();
if (t === q) return WEIGHTS.exact;
if (t.startsWith(q)) return WEIGHTS.prefix;
if (t.includes(q)) return WEIGHTS.substring;
return 0;
}
// Trust the server for now: whatever arrives, hand it on.
export function parseNotes(text: string) {
return JSON.parse(text);
}npx tsc --noEmitexit code: 0 — no errors reportedThe check is green, and that is exactly the trap this step exists to expose. parseNotes still returns whatever JSON.parse gives — the type any — and any silences the compiler completely: main.ts gets an untyped value and calls rank with it, and nobody objects. A green check is only as strong as the types it checked. Make the parser honest:
// Be honest about what we know: JSON.parse could return anything.
export function parseNotes(text: string): unknown {
return JSON.parse(text);
}src/main.ts(12,20): error TS2345: Argument of type 'unknown' is not
assignable to parameter of type 'Note[]'.One word turned silence into a report at the exact call site that consumes unproven data. That is unknown versus any in miniature: any is a lie everyone believes, unknown is a question that demands an answer. Step 5 answers it.
06. Step 5: validate the payload and finish main
Replace the trusting parser with a discriminated union of outcomes, and a validator built from the checks the narrowing lesson taught: typeof, in, Array.isArray, and a type predicate to certify the element shape. The final module:
export type Note = { id: string; title: string };
export type ParseResult =
| { ok: true; notes: Note[] }
| { ok: false; error: string };
const MAX_RESULTS = 5;
const WEIGHTS = { exact: 3, prefix: 2, substring: 1 } as const;
export function rank(notes: Note[], query: string) {
const q = query.trim().toLowerCase();
const scored: { note: Note; score: number }[] = [];
for (const note of notes) {
const score = scoreNote(note.title, q);
if (score > 0) scored.push({ note, score });
}
scored.sort((a, b) => b.score - a.score);
return scored.slice(0, MAX_RESULTS);
}
function scoreNote(title: string, q: string): number {
const t = title.toLowerCase();
if (t === q) return WEIGHTS.exact;
if (t.startsWith(q)) return WEIGHTS.prefix;
if (t.includes(q)) return WEIGHTS.substring;
return 0;
}
// Be honest about what we know: JSON.parse could return anything.
export function parseNotes(text: string): ParseResult {
let data: unknown;
try {
data = JSON.parse(text);
} catch {
return { ok: false, error: 'response is not JSON' };
}
if (!isNoteList(data)) {
return { ok: false, error: 'expected a list of notes' };
}
return { ok: true, notes: data };
}
function isNoteList(value: unknown): value is Note[] {
return Array.isArray(value) && value.every(isNote);
}
function isNote(value: unknown): value is Note {
if (typeof value !== 'object' || value === null) return false;
if (!('id' in value) || !('title' in value)) return false;
return typeof value.id === 'string' && typeof value.title === 'string';
}import { parseNotes, rank } from './search.js';
const payload = `[
{"id": "n1", "title": "Union types"},
{"id": "n2", "title": "Type narrowing"},
{"id": "n3", "title": "Utility types"}
]`;
const parsed = parseNotes(payload);
if (!parsed.ok) throw new Error(`Bad data: ${parsed.error}`);
const { notes } = parsed;
for (const query of ['ty', 'union', 'zig']) {
const top = rank(notes, query)[0];
console.log(query, '->', top ? top.note.title : '(no match)');
}npx tsc --noEmit
npm start # script: tsx src/main.ts> [email protected] start
> tsx src/main.ts
ty -> Type narrowing
union -> Union types
zig -> (no match)Zero type errors, and the output is line-for-line the contract from step 1. Each fix earned its place: the try/catch handles JSON.parse throwing; if (!parsed.ok) narrows the result union so parsed.notes is read only after the check; and the guard around top is what noUncheckedIndexedAccess demanded, because rank(...)[0] is now T | undefined. The JavaScript had these three holes all along; strict mode turned them into compiler questions.
07. Step 6: prove the validator rejects bad data
A validator is code, so it needs evidence too. Feed it the payloads it exists to catch: a good list, an object in place of a list, a note with a numeric id, and text that is not JSON at all:
import { parseNotes } from './search.js';
const cases = [
'[{"id": "n1", "title": "Union types"}]',
'{"notes": []}',
'[{"id": 7, "title": "Numeric id"}]',
'not json at all',
];
for (const payload of cases) {
const result = parseNotes(payload);
console.log(
result.ok ? `ok: ${result.notes.length} notes` : `rejected: ${result.error}`,
);
}npx tsx src/check-parse.tsok: 1 notes
rejected: expected a list of notes
rejected: expected a list of notes
rejected: response is not JSONEach malformed payload becomes a reason instead of a crash: a UI that can say "unexpected data from the server" rather than show a blank screen and a console error.
08. Step 7: make the check a habit
The conversion only counts if it keeps counting, so add the check as a script:
npm pkg set scripts.check="tsc --noEmit"
npm run check> [email protected] check
> tsc --noEmitSilence after the banner means clean. In a frontend project the same command runs before the bundler — tsc --noEmit && vite build is the common shape — and in CI it is the step that blocks a red type from reaching main.
09. Step 8: use a package that ships no types
Real projects call code they did not write, and the compiler can check those calls only if it has a declaration file for the package: a .d.ts file that holds types and no runnable code. Many packages ship one; some do not. To see what happens then, run mkdir -p vendor/slugify-lite, add these two files, and install the folder as a package:
{
"name": "slugify-lite",
"version": "1.0.0",
"type": "module",
"exports": "./index.js"
}// Turns "Type narrowing" into "type-narrowing" for use in a URL.
export function slugify(text) {
return text
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '');
}npm install ./vendor/slugify-liteadded 1 package, and audited 8 packages in 6s
found 0 vulnerabilitiesnpm links node_modules/slugify-lite to the folder and records "slugify-lite": "file:vendor/slugify-lite" under dependencies. Now import it; the second import brings in the Note type that the final search.ts exports:
import { slugify } from 'slugify-lite';
import type { Note } from './search.js';
export function noteLink(note: Note): string {
return `/notes/${note.id}/${slugify(note.title)}`;
}
console.log(noteLink({ id: 'n2', title: 'Type narrowing' }));npm run check> [email protected] check
> tsc --noEmit
src/links.ts(1,25): error TS7016: Could not find a declaration file for module
'slugify-lite'. '/home/learner/search-ts/vendor/slugify-lite/index.js' implicitly
has an 'any' type.
Try `npm i --save-dev @types/slugify-lite` if it exists or add a new declaration
(.d.ts) file containing `declare module 'slugify-lite';`Under strict, an untyped import is an error rather than a silent any: the noImplicitAny rule from step 2, applied to a whole package. Try the fixes in this order:
- Does the package ship types? A
typesfield in itspackage.json, or atypescondition inexports, means the compiler finds them by itself. Zod, from the narrowing lesson, works this way. - Are there community types? Many popular JavaScript-only packages have declarations in the DefinitelyTyped project, published as
@types/<name>: runnpm install --save-dev @types/<name>, as the message suggests. - Neither? Write a short declaration that covers only what you call:
// Describes only the part of slugify-lite that this project calls.
declare module 'slugify-lite' {
export function slugify(text: string): string;
}npm run check
npx tsx src/links.ts> [email protected] check
> tsc --noEmit
/notes/n2/type-narrowingdeclare module 'slugify-lite' is an ambient declaration: it says that a module with this name exists and what it exports, without supplying any code. tsc finds the file because include covers src. It trusts the file completely and never compares it with index.js, so keep it short and accurate. A related form, declare global { … }, adds names to the global scope instead, such as a property a third-party script puts on window.
import type marks an import used only for types, so it is removed from the JavaScript that runs. A plain import { Note } also works here, because tsx and tsc drop imports used only as types. But under the verbatimModuleSyntax option tsc reports it as TS1484, and Node's built-in type stripping fails at runtime, so use import type for types.
10. Check your understanding
11. Apply it
Run the same conversion on a second module of your own, such as the note store from the DOM events lab, which reads localStorage, data you do not control. Keep the same order: checkJs, rename, annotate, then make every any honest before validating. The full skill practice — the async search UI under strict and noUncheckedIndexedAccess, a discriminated union for the API result, schema validation as in the narrowing lesson, and zero type errors without any — is now within reach; the skill page links the practice brief and the knowledge check.
12. Review prompt
Without looking back: what were the five compiler errors after the rename, and which two features of the final module resolved them? Name the three ways to give the compiler types for a dependency, in the order you try them, and say what import type changes. Finally, explain why the lab ran node src/main.js before touching anything.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.