TypeScript in One Lesson

Updated · 8 min read
mediumES2026javascripttypescripttypes

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 interface or type; 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 .ts files directly by stripping types; run tsc --noEmit separately to check them.

The Same Function in JavaScript and TypeScript

fees.ts▶ Try it
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 }));
Output
Srihitha: $97 due

The 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:

mistakes.ts
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

FeatureExample
Basic typesstring, number, boolean, bigint, null, undefined
Arraysnumber[] or Array<number>
Object shapesinterface Payment { name: string; amount: number; note?: string } (? = optional)
Type aliasestype Cents = number;
Union typestype Method = "card" | "check" | "ach";
Function types(amount: number) => string
Genericsfunction first<T>(items: T[]): T | undefined
Type inferenceconst fee = 120; is inferred as number without an annotation
unknownA value of any type that must be checked before use (safer than any)
features.ts▶ Try it
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[]));
Output
[
  'Navika paid $120.00 by paper check (Fall term)',
  'Advitha paid $45.00 by bank transfer'
]
Navika undefined

The 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

CommandDoes
node file.tsRuns it in Node.js 26 by stripping types (erasable syntax only; no checking)
npx tsc --noEmitType-checks the project without producing files
npx tscChecks and compiles .ts to .js (for older runtimes or publishing)
Vite, esbuildStrip 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):

jsdoc.js▶ Try it
// @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 }));
Output
Navika: $120

This is a gentle way to add type checking to an existing JavaScript project without converting files.

When to Adopt TypeScript

Good fitLess needed
Teams, and code that many people changeSmall scripts and one-off tools
Long-lived applications and librariesPrototypes you'll throw away
Complex data (API responses, state)Very dynamic code that's hard to type
Refactoring large codebasesLearning 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:

money.ts▶ Try it
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.
Output
$250.50

The "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
by-method.ts▶ Try it
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"));
Output
165 0

Quick check: TypeScript

3 questions
1What happens to TypeScript types at run time?
2What does node file.ts do in Node.js 26?
3Which type allows only the values "card", "check" or "ach"?

Key Takeaways

TaskExample
Annotate a parameterfunction f(days: number): number
Object shapeinterface Payment { amount: number }
Fixed set of valuestype Method = "card" | "check"
Genericfunction first<T>(xs: T[]): T | undefined
Check a projectnpx tsc --noEmit
Run a filenode file.ts

Was this tutorial helpful?

Lesson 129 of 139