Back to Explore
GuideVibeFix editorialUpdated Nov 25, 2026

Adding Types to JavaScript: TypeScript Basics, Run Directly on Node 24

Same 5 books, same 150930 cents, now with types: Three-Body at 10% off is 37737 cents, saving 4193; a type guard blocks a fake book; enum and parameter properties exit 1, a mistyped program exits 0. Node v24.22.1, measured.

Real photo: code on two monitors in an office, the nearest screen filling the frame

JavaScript has an old weakness: pass a string where a number was expected, and it either quietly converts it for you or blows up far away from where the mistake was made, with the error and the cause separated by a long distance. TypeScript adds a layer of types on top of JavaScript: you state what each thing is supposed to look like while you write the code, and mistakes get caught before the program runs. Even better, since Node.js 22.18.0, a .ts file can run directly — no compilation, no packages to install. Node.js strips the type parts away first, then runs the remaining JavaScript. This guide teaches TypeScript basics that way: the same fictional Morning Light Bookshop, the same 5 books, the same total of 150930 cents — except that this time, every book has a type. The examples and numbers are invented to make the ideas clear; they are not real records. But every step was really run: the demo script is demo251_g2.ts, on Node v24.22.1, and the Chinese and English runs execute the same logic, so the numbers are identical. Each transcript is saved in this directory.

Here is the conclusion up front: the 5 books still total 150930 cents, 35 copies; Three-Body at 10 percent off is 37737 cents, saving 4193 cents from the full price of 41930 cents; a union-typed id of type number | string takes the number branch for a number and the string branch for a string; the generic first takes the head of any array and returns undefined for an empty array; the category table has only 2 entries and is frozen by as const; a type guard blocked a fake book JSON; and of the three traps, enum and parameter properties both fail with exit code 1 and the error ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX, while a plainly mistyped program still exits 0 and prints n = oops typeof n = string. Keep those numbers in mind — everything that follows is their expansion.

Interfaces and annotations: give a book a shape first

The two most-used words in TypeScript are "interface" and "type annotation". An interface gives something a shape: which fields it has and what type each field is. An annotation writes that shape into the code. A bookshop book is defined like this:

interface Book {
  title: string;
  price: number; // integer cents
  stock: number;
  discount?: number; // optional: 0.9 means 10% off
}

const BOOKS: Book[] = [
  { title: "Three-Body", price: 5990, stock: 7 },
  { title: "Twenty Thousand Leagues", price: 3950, stock: 12 },
  { title: "To Live", price: 2900, stock: 5 },
  { title: "Siddhartha", price: 4500, stock: 3 },
  { title: "West with the Night", price: 4200, stock: 8 },
];

function total(books: Book[]): number {
  return books.reduce((s: number, b: Book) => s + b.price * b.stock, 0);
}

The official handbook says the three most common primitive types are string, number, and boolean, with the same names the typeof operator returns; JavaScript has no separate integer type — every number is a number. An annotation always goes after the thing it annotates — after the variable name, after the parameter name, after the parameter list — never before it, the way some other languages do it. BOOKS: Book[] means "an array of Book", and total(books: Book[]): number means "takes a Book array and returns a number".

The numbers come out exactly the same as in the previous Node.js guide: Three-Body 41930 cents, Twenty Thousand Leagues 47400 cents, To Live 14500 cents, Siddhartha 13500 cents, West with the Night 33600 cents, a total of 150930 cents, or 1509.30 yuan, 35 copies. Types do not change a single number; they change what happens when you write something wrong. Write one book's price as the string "5990", and TypeScript tells you the type is wrong while you are still writing the code; plain JavaScript would run silently until the maths step produced a strange result. The handbook adds a sentence beginners most often miss: most of the time you do not need to write annotations at all, because TypeScript infers the type from the initial value — let myName = "Alice" needs no annotation; it already knows it is a string. My judgment: put annotations where mistakes are easy and worth preventing — function parameters and return values, interface fields. Putting them where the answer is obvious at a glance, such as let count = 0, is pure clutter.

Unions and narrowing: one id, maybe a number, maybe a string

Real-world data is often "either of two things": an order id is sometimes the number 101, sometimes the string "202". A union type writes both possibilities side by side:

function printId(id: number | string): string {
  if (typeof id === "string") {
    return id.toUpperCase();
  }
  return String(id);
}

printId(101);    // number branch, id = 101
printId("202");  // string branch, id = 202

number | string reads as "number or string" — the vertical bar means "or". The key is the next line: the check typeof id === "string" does more than split the runtime into branches; it also narrows the type. Inside the branch where the check holds, id is a string and toUpperCase() is allowed; in the branch where it does not hold, id is only a number. The official handbook calls this process "narrowing": TypeScript deduces a more specific type for a value based on the structure of the code.

typeof is not the only way to narrow. Another common example from the handbook is Array.isArray: a value that may be a string[] or a string — inside the branch where Array.isArray(x) holds, x is an array and join(" and ") is allowed; in the branch where it does not hold, x is only a string. The check and the narrowing are the same thing: typeof splits primitive types, Array.isArray splits arrays from non-arrays, instanceof splits instances of a class, and the in operator splits on "does it have this property". When writing code, first decide "which two cases am I splitting", then pick the matching check. Get the check right and the type narrows along with it, and once the narrowing is right, everything you may call afterwards is right too.

What you cannot do before narrowing, you can do after it — that is the rule for unions. You cannot call toUpperCase() directly on a number | string value, because if it happens to be a number, that method does not exist. The handbook's example states it plainly: TypeScript only allows an operation if it is valid for every member of the union; to do something specific to one member, first narrow the range with code. Both demo calls ran fine: printId(101) took the number branch and printed id = 101; printId("202") took the string branch and printed id = 202. A side note: the site's JavaScript guide on optional chaining and nullish coalescing covers the runtime operators ?. and ??, which are JavaScript syntax itself; the narrowing in this guide is a judgment TypeScript makes at the type level. They solve problems on different layers — do not mix them up.

Optional properties: discounted books and full-price books

Not every book has a discount. A question mark after a field name in an interface means "this field may be absent":

interface Book {
  title: string;
  price: number;
  stock: number;
  discount?: number; // optional: 0.9 means 10% off
}

discount?: number means a book may carry a discount, or may not. The demo gives Three-Body a 10 percent discount:

const discounted: Book = { ...BOOKS[0], discount: 0.9 };
Math.round(discounted.price * discounted.stock * discounted.discount);
// 41930 x 0.9, rounded to 37737 cents

Three-Body's full line price is 41930 cents; at 10 percent off it is 41930 times 0.9, which is 37737 cents, saving 4193 cents — the two bars on the left of the chart are those two numbers. To Live has no discount property, so its full price stands at 14500 cents. Note the Math.round here: 0.9 cannot be stored exactly in binary floating point, so the raw product of 41930 times 0.9 carries a tiny tail; only after rounding is it a clean 37737. The previous guide said money should be kept as integer cents; a discount is a multiplication, and after multiplying you must round back to an integer immediately, or the fractional tail sneaks back into the books.

An optional property comes with a matching rule: before reading it, confirm it is there. The handbook's example is last?: string: calling obj.last.toUpperCase() directly fails, because when last was not provided it is undefined. Either check obj.last !== undefined first, or use obj.last?.toUpperCase(). The demo writes discounted.discount as number, which says "I guarantee it has a value here" — but that promise is made to the type checker, and nothing enforces it at runtime. If the book actually has no discount, the product is NaN. My judgment: use as assertions rarely, and each time ask yourself "if my guarantee is wrong, what happens to the program". Where a check and narrowing can solve it, prefer the check and the narrowing.

Generics: one first() takes the head of any array

Taking the first element of an array has nothing to do with what the array holds: books, numbers, or strings, the action is the same. A generic leaves "what it holds" blank, as a placeholder:

function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

first(BOOKS); // the first book: Three-Body
first([]);    // undefined

The T inside <T> is that placeholder, read as "some type". You do not fill it in when you call the function; TypeScript infers it from the array you pass. Pass BOOKS and T is Book, so the return is Book | undefined; pass an empty array and the return is undefined. Both demo calls ran: first(BOOKS) is the first book, Three-Body, and first([]) is undefined.

A note on the two spellings: T[] and Array<T> mean exactly the same thing — the handbook uses both, so pick one and stay with it. The demo uses T[] because it is shorter. Generics are not only for functions, either: interfaces and classes can carry them too, such as the handbook's GenericIdentityFn<Type> and GenericNumber<NumType>. But note that a generic class is only generic over its instance side; static members cannot use the class's type parameter. This guide only needed generics on functions, which is enough to explain "one action, many types"; generics on interfaces and classes can wait.

Why does the return type carry | undefined? Because an empty array has no first element, and arr[0] is undefined. This is the detail most people miss when they write generics: they think only about what the normal case returns and forget what the edge case returns. The benefit of TypeScript is right here — once the return type is written as T | undefined, the caller must handle the undefined possibility, or the type check fails. My judgment: when writing a generic, think about the edge case first and the normal case second; a generic function that never considered the empty array will sooner or later fail at night on undefined.

as const and readonly: a constant table that must not change

The bookshop's category table has only two entries, fiction and nonfiction, written directly in the code:

const CATEGORIES = ["fiction", "nonfiction"] as const;
// the table has 2 categories, the first is fiction, frozen by as const

as const means "understand this value as a constant": each item is no longer a broad string but the exact literal "fiction" or "nonfiction", and the whole array is frozen — nothing can be added to it and no item can be changed. The demo prints: the table has 2 categories, the first is fiction. Without as const, the array's type would be string[], and a misspelled category slipped into it would raise no objection; with it, one wrong letter in a category fails the type check.

readonly often appears alongside as const: written before an interface field, it means the field can be read but not changed. The two have different jobs: as const is written after a value and freezes the literal; readonly is written in a type and locks the field. When should you use them? My judgment: freeze anything where a change would cause trouble — category tables, status lists, constants in configuration are typical cases. But do not freeze things that change often: freeze the wrong place and every edit fills the code with errors, wiping out the benefit of freezing at all.

Type guards: JSON read back, check it is really a book

The previous guide left a loose end: the types of what JSON.parse returns are decided entirely by the file's contents, and if the file was edited, the maths goes wrong. A type guard exists for exactly this problem:

function isBook(x: unknown): x is Book {
  return (
    typeof x === "object" &&
    x !== null &&
    typeof (x as Book).title === "string" &&
    typeof (x as Book).price === "number" &&
    typeof (x as Book).stock === "number"
  );
}

const parsed: unknown = JSON.parse(
  JSON.stringify({ title: "Three-Body", price: 5990, stock: 7 })
);
if (isBook(parsed)) {
  // guard passed: the JSON read back is really a book,
  // title Three-Body, line total 41930 cents
}

Read isBook(x: unknown): x is Book slowly: the parameter is unknown, meaning "I do not know what this is"; the return is x is Book, meaning "if this function returns true, then x is a Book". The body checks one thing at a time: it is an object, it is not null, title is a string, price is a number, stock is a number. After the check passes, inside the if branch parsed is treated as a Book: you can take parsed.title directly and compute parsed.price * parsed.stock, which is 41930 cents.

The demo also prepared a fake record: {"title":42,"price":"cheap"}, with a numeric title and a string price. The type guard blocked it, printing that it is not a book. That blocking is the whole value of a type guard: it turns an error discovered only at runtime into an error discovered at the door. The difference between unknown and any sits here too: any means "use it however you like, the checker does not care", while unknown means "prove who you are first, then get to work". The handbook's advice is clear: any is convenient when you do not want to write out a type, but it switches type checking off; for something you are unsure about, write unknown first and narrow it with a guard. My judgment: all data that comes from outside — files, networks, user input — goes through unknown first and then a guard, never straight into an assertion of the type you want. An assertion is "trust"; a guard is "verify". A failed verification reports an error at worst; a misplaced trust corrupts the whole set of books.

Three traps: being able to run and being checked are two different things

This is the most important section of the guide. Node.js runs .ts files directly through "type stripping": it deletes the syntax that only affects types and never affects runtime — annotations, interfaces, type aliases — and runs the remaining JavaScript. The official docs state it plainly: from 22.18.0 onward, if the code contains only "erasable TypeScript syntax", node example.ts just works, with no flags; but it does not type-check your code — to catch type errors, run npx tsc --noEmit separately. The three traps below are direct consequences of that sentence.

The first trap is enums:

enum Color { Red = "red", Blue = "blue" }
console.log(Color.Red);

Running node demo251_g2_trap_enum.ts exits with code 1 and the error SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript enum is not supported in strip-only mode. An enum fails because it is more than a type: an enum really creates an object at runtime, so deleting it would delete code, and type stripping cannot do that — it can only refuse. The second trap is a constructor parameter property:

class Counter {
  constructor(private count: number) {}
  get value(): number { return this.count; }
}

Again exit code 1, with the error TypeScript parameter property is not supported in strip-only mode. A parameter property is also syntax that cannot be deleted: it does more than declare a parameter — it generates assignment code behind the scenes. The official docs name both in the list of things type stripping does not support, along with namespaces that carry runtime code and import aliases. The three bars on the right of the chart are the exit codes of these three traps: enum 1, parameter property 1, no type check 0.

The third trap is the easiest to misunderstand, and the most dangerous:

const n: number = "oops";
console.log("n =", n, "typeof n =", typeof n);

Running node demo251_g2_trap_nocheck.ts exits with code 0 and prints n = oops typeof n = string. A plain type error — a string placed where a number belongs — runs to completion anyway, because Node.js strips types but never checks them. By runtime the annotation has been stripped away, leaving plain const n = "oops", the most ordinary JavaScript. My judgment: keep "it runs" and "it is correct" apart. That node xxx.ts runs proves only that the syntax can be stripped, not that the types are right; proving the types are right needs a separate type check. The officially recommended setup is the same: run with Node.js directly during development for fast feedback, and run tsc --noEmit separately or in CI for the type check. The site already has a TypeScript strict mode guide, which covers how the strict switches in tsconfig are configured; this guide covers how the language itself is written. The division of labor is: that guide controls "how strict the checking is", this one covers "how types are written".

What you can do after this guide — and where it stops

After this guide, you should be able to do seven things: define interfaces and write type annotations, knowing that inference lets you write fewer annotations most of the time; use a union type for "either of two things" and narrow it with typeof until it can be worked with; use optional properties for fields that "may be absent" and confirm they exist before reading them; write a generic function that works for any array, with the empty array's undefined written into the return type; freeze a constant table that must not change with as const; verify JSON from outside with a type guard; and tell apart the three lines of Node.js type stripping — enum and parameter properties do not run, mistyped code still runs, and checking types needs a separate tsc run.

Bar chart comparing Three-Body at full price 41930 cents with 10 percent off at 37737 cents, and exit codes of the 3 traps: enum 1, parameter property 1, no type check 0

The boundary of this guide also needs stating. The site's JavaScript series covers JavaScript in the browser; this guide covers the basics of the TypeScript language, and the two are not the same thing: knowing JavaScript is not the same as knowing TypeScript — the difference is exactly the layer of types. The site's TypeScript strict mode guide covers configuration; this guide covers how to write types, so match each to its job when reading. The previous Node.js guide covers the runtime — files, paths, HTTP, error codes; this guide covers the type layer of the same code. The two guides share one bookshop and one set of numbers, and together they are the two halves of "writing code that runs" and "having that code checked before it runs".

Three things to try yourself, none needing any package: add a category field to the Book interface, typed as "fiction" | "nonfiction", then deliberately pass in a "comic" and see what happens when Node.js runs it directly — the answer is that it runs anyway, because nobody checks; then rewrite the category table without as const and compare what the inferred type becomes; finally, add a check to isBook that blocks a book whose stock is negative, and feel how a guard fills the gap when "the type is right but the value is wrong". Once types feel natural to write, install the TypeScript compiler and run npx tsc --noEmit — that is when you will see every error that "ran anyway" in this guide caught, exactly as written.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles