TypeScript in One Lesson
TypeScript is JavaScript with type annotations: you describe what kind of value each variable, parameter and return value holds, and the TypeScript compiler checks your whole program for mismatches before it runs. It catches whole families of the bugs from "Common JavaScript Mistakes" (a string where a number was expected, a property that doesn't exist, a forgotten await) while you type, in your editor. TypeScript compiles to plain JavaScript; the types disappear at run time. This lesson shows what it adds, with the same Fee Tracker code in both languages, so you can decide when it's worth adopting.
In One Minute
- TypeScript = JavaScript + types. Every JavaScript program is (nearly) a valid TypeScript program.
- Annotate with
: type:function lateFee(days: number): number. - Describe object shapes with
interfaceortype; combine with unions ("card" | "check") and generics (Array<Payment>). - The type checker (
tsc, or your editor) reports errors before running; types are erased at run time. - Node.js 26 runs
.tsfiles directly by stripping types; runtsc --noEmitseparately to check them.
The Same Function in JavaScript and TypeScript
interface Student {
name: string;
balance: number;
daysLate: number;
}
function lateFee(daysLate: number, rate: number = 2): number {
return Math.min(Math.max(daysLate - 10, 0) * rate, 30);
}
function reminder(student: Student): string {
return `${student.name}: $${student.balance + lateFee(student.daysLate)} due`;
}
console.log(reminder({ name: "Srihitha", balance: 85, daysLate: 16 }));function lateFee(daysLate, rate = 2) {
return Math.min(Math.max(daysLate - 10, 0) * rate, 30);
}
function reminder(student) {
return `${student.name}: $${student.balance + lateFee(student.daysLate)} due`;
}
console.log(reminder({ name: "Srihitha", balance: 85, daysLate: 16 }));Srihitha: $97 dueThe TypeScript version ran directly in Node.js 26, which removes the type annotations and runs the JavaScript that's left. The output is identical: types change nothing at run time. What they change is what the editor and compiler know.
What the Type Checker Catches
Here are mistakes that JavaScript runs silently (producing wrong results), and the errors TypeScript reports before running:
reminder({ name: "Navika", balance: "120", daysLate: 3 });
// error TS2322: Type 'string' is not assignable to type 'number'.
reminder({ name: "Navika", balance: 120 });
// error TS2345: Argument of type '{ name: string; balance: number; }' is not assignable
// to parameter of type 'Student'. Property 'daysLate' is missing in type
// '{ name: string; balance: number; }' but required in type 'Student'.
const s: Student = { name: "Advitha", balance: 45, daysLate: 0 };
console.log(s.balnce);
// error TS2551: Property 'balnce' does not exist on type 'Student'. Did you mean 'balance'?
const label = fetchTotal() + 1; // fetchTotal returns Promise<number>
// error TS2365: Operator '+' cannot be applied to types 'Promise<number>' and '1'.These messages come from TypeScript 6.0 (tsc --noEmit --strict). Each is a real bug from earlier lessons (a string from a form, a missing field, a typo, a forgotten await), caught at the moment it's typed instead of in production.
The Main Type Features
| Feature | Example |
|---|---|
| Basic types | string, number, boolean, bigint, null, undefined |
| Arrays | number[] or Array<number> |
| Object shapes | interface Payment { name: string; amount: number; note?: string } (? = optional) |
| Type aliases | type Cents = number; |
| Union types | type Method = "card" | "check" | "ach"; |
| Function types | (amount: number) => string |
| Generics | function first<T>(items: T[]): T | undefined |
| Type inference | const fee = 120; is inferred as number without an annotation |
unknown | A value of any type that must be checked before use (safer than any) |
type Method = "card" | "check" | "ach";
interface Payment {
name: string;
amountCents: number;
method: Method;
note?: string;
}
function first<T>(items: T[]): T | undefined {
return items[0];
}
function describe(p: Payment): string {
const how = p.method === "card" ? "card" : p.method === "check" ? "paper check" : "bank transfer";
return `${p.name} paid $${(p.amountCents / 100).toFixed(2)} by ${how}${p.note ? ` (${p.note})` : ""}`;
}
const payments: Payment[] = [
{ name: "Navika", amountCents: 12000, method: "check", note: "Fall term" },
{ name: "Advitha", amountCents: 4500, method: "ach" },
];
console.log(payments.map(describe));
console.log(first(payments)?.name, first([] as number[]));[
'Navika paid $120.00 by paper check (Fall term)',
'Advitha paid $45.00 by bank transfer'
]
Navika undefinedThe union Method means the checker rejects method: "cash". The generic first<T> returns the same type it receives, so first(payments) is known to be a Payment (or undefined), and the editor can autocomplete .name.
Running and Checking TypeScript
| Command | Does |
|---|---|
node file.ts | Runs it in Node.js 26 by stripping types (erasable syntax only; no checking) |
npx tsc --noEmit | Type-checks the project without producing files |
npx tsc | Checks and compiles .ts to .js (for older runtimes or publishing) |
| Vite, esbuild | Strip types while bundling front-end code (check with tsc separately) |
Node.js's type stripping handles erasable TypeScript: annotations, interfaces and type aliases that can simply be deleted. Features that generate code (enum, namespace, constructor parameter properties) need --experimental-transform-types or a compiler. A tsconfig.json with "strict": true turns on the checks that catch the most bugs.
Types Without TypeScript: JSDoc
You can get most of the editor benefits in plain .js files with JSDoc comments; TypeScript's checker reads them (add // @ts-check at the top, or "checkJs": true in tsconfig.json):
// @ts-check
/**
* @typedef {{ name: string, balance: number }} Student
*/
/**
* @param {Student} student
* @returns {string}
*/
function label(student) {
return `${student.name}: $${student.balance}`;
}
console.log(label({ name: "Navika", balance: 120 }));Navika: $120This is a gentle way to add type checking to an existing JavaScript project without converting files.
When to Adopt TypeScript
| Good fit | Less needed |
|---|---|
| Teams, and code that many people change | Small scripts and one-off tools |
| Long-lived applications and libraries | Prototypes you'll throw away |
| Complex data (API responses, state) | Very dynamic code that's hard to type |
| Refactoring large codebases | Learning JavaScript fundamentals for the first time |
The professional tooling add-on goes further: configuration, strict mode, generics in depth, typing existing JavaScript, and declaration files for libraries.
In Practice
The Fee Tracker's money module in TypeScript: a branded Cents type keeps dollars and cents from being mixed up, and the function types document exactly what goes in and out:
type Cents = number & { readonly __brand: "Cents" };
const toCents = (dollars: number): Cents => Math.round(dollars * 100) as Cents;
const addCents = (a: Cents, b: Cents): Cents => (a + b) as Cents;
const formatCents = (c: Cents): string =>
new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(c / 100);
const total = [120, 85.5, 45].map(toCents).reduce(addCents, 0 as Cents);
console.log(formatCents(total));
// formatCents(120) would be a type error: a plain number isn't Cents.$250.50The "brand" exists only for the checker; at run time, Cents values are ordinary numbers.
Common Mistakes
Thinking types validate data at run time. They don't; validate external input.
Using any to silence errors. It turns checking off. Use unknown and narrow it with checks.
Running .ts without ever type-checking. Node.js strips types without checking them. Run tsc --noEmit.
Over-annotating. Let inference work: const fee = 120 needs no : number.
Practice
Challenge: Write a TypeScript function totalByMethod(payments: Payment[], method: Method): number that sums the amounts paid with one method, and run it.
Show solution
type Method = "card" | "check" | "ach";
interface Payment { name: string; amount: number; method: Method }
function totalByMethod(payments: Payment[], method: Method): number {
return payments.filter((p) => p.method === method).reduce((sum, p) => sum + p.amount, 0);
}
const payments: Payment[] = [
{ name: "Navika", amount: 120, method: "card" },
{ name: "Srihitha", amount: 85, method: "check" },
{ name: "Advitha", amount: 45, method: "card" },
];
console.log(totalByMethod(payments, "card"), totalByMethod(payments, "ach"));165 0Key Takeaways
| Task | Example |
|---|---|
| Annotate a parameter | function f(days: number): number |
| Object shape | interface Payment { amount: number } |
| Fixed set of values | type Method = "card" | "check" |
| Generic | function first<T>(xs: T[]): T | undefined |
| Check a project | npx tsc --noEmit |
| Run a file | node file.ts |
Was this tutorial helpful?