15 min read
TypeScript in Node.js: native, no compiling
In one sentence: TypeScript is JavaScript with types: annotations that say what kind of data goes where, so the editor and tsc warn you about a mistake before anything runs. Node.js runs your .ts files by erasing the types, without compiling them and without checking them.
What you will learn
- Describe the shop's data with annotations, interface and type, including unions of fixed values.
- Tell unknown from any, and check a piece of data that comes from outside before using it.
- Explain what Node does with a .ts file and why it doesn't catch type errors.
- Check the types with tsc --noEmit and recognize the syntax Node can't erase, such as enum.
Before you start, read: 02-javascript.md
The problem
Section titled “The problem”Imagine the shop’s API stores the mug’s price as text, '8.5', instead of as a number, 8.5: someone typed it by hand into a JSONJSON stands for JavaScript Object Notation.A format for writing data as text, with braces, quotes and colons: {"product":"mug","quantity":2}. People can read it, and so can almost any programming language, and it’s the most common format for the data that travels between a frontend and a backend.Go to definition file. Two mugs, '8.5' * 2, give 17, and everything seems fine. But with €2 of shipping, '8.5' + 2 gives 8.52: JavaScriptThe programming language of web pages, which, with Node.js, is also used outside the browser to write servers. A JavaScript program is text with instructions that run one after another.Go to definition has glued them together as text.
JavaScript doesn’t complain: it decides on the fly what to do with each piece of data. You find out when a customer sees a total of €8.52 in their cart. And a server receives data from many places: the bigger it grows, the easier it is for one piece to arrive with the wrong shape.
TypeScriptA language that is JavaScript with types: annotations that say what kind of data goes in each place, such as a number or a piece of text. The editor and the TypeScript checker warn about errors before the program runs, and Node.js runs it by erasing the types.Go to definition lets you write down what shape each piece of data has, and a program checks all your code against that description before running it. In this lesson you move the shop’s code to TypeScript and see which mistakes it catches, and which it doesn’t.
The analogy
Section titled “The analogy”The analogy
Think of a government form. Each box says what goes in it: “Date (mm/dd/yyyy),” “Amount in euros.” Those instructions are the types.
Before you hand it in, the clerk at the counter checks the whole thing and marks it in red: “you’ve put letters where a number goes.” That checker is tsc, TypeScript’s checker, and its red pen is your editor’s underline.
Then the form gets processed. Whoever processes it no longer reads the instructions on the boxes, only what you wrote: that’s Node.
Where the analogy breaks down
- The clerk only checks the form you fill in. The papers that come to you from outside, like the JSON a client sends you, nobody checks against those boxes: that’s done when you receive them, in lesson 7, “Validation”.
- A form that hasn’t been checked doesn’t get processed. A
.tsfile with type errors does: Node runs it anyway, with the mistake inside. - Someone else designs the boxes on the form. You write the types yourself, and if you write them wrong, the checker compares against the wrong model.
How it really works
Section titled “How it really works”A type says what kind of data goes where
Section titled “A type says what kind of data goes where”This is JavaScript from lesson 2, “JavaScript”, with something new: a colon and a word after each name.
const price: number = 8.5;const name: string = 'Mug';const available: boolean = true;: number is an annotation: it says that price is a number. string is text, and boolean is a yes or a no (true or false). Each one is a TypeThe kind of data that can go in a place, such as a number, a piece of text or a product with its name and its price. In TypeScript it’s written after a colon (price: number), and it helps find errors before running the program.Go to definition: the kind of data that can go in a place.
You don’t need to annotate everything: in const price = 8.5, TypeScript works out on its own that it’s a number (inference). You write types where it can’t guess them: in the shape of your data and in what each function receives.
An interface describes an object: the product
Section titled “An interface describes an object: the product”The shop’s products are ObjectA value that groups several pieces of data, each with its own name, such as { name: "Mug", price: 8.5 }. Each piece is read with a period and its name, such as product.price.Go to definition with three pieces of data. This is their type, at the top of src/products.ts:
// Types say what shape each piece of data has. Node erases them when it runs the code: they're// there so the editor and tsc warn you about errors before the program ever runs.export interface Product { id: number; name: string; price: number;}interface Productgives a name to a shape: everyProducthas a numericid, anamethat is text and a numericprice. With it, the mug with the price'8.5'is no longer a valid product.exportis new: it lets other files useProduct. Each file is a ModuleA code file that offers some of its pieces to other files, which bring them in with import. This way a program is split across several files and can use the pieces that come with Node.js or with a package.Go to definition, and another file can only bring in withimportwhat this one exports, just as you brought inreadFilefrom Node in lesson 1, “Node.js”. Here,src/main.tswill bring it in.
type, unions and literal types: an order’s status
Section titled “type, unions and literal types: an order’s status”An order at the shop is pending, paid or shipped. Nothing else:
// An order can only be in one of these three states.export type OrderStatus = 'pending' | 'paid' | 'shipped';
export interface Order { id: number; productId: number; quantity: number; status: OrderStatus;}type OrderStatus = …also gives a name to a type.'pending' | 'paid' | 'shipped'is a union: the bar|reads as “or.” Each option is a literal type, one specific value: only those three values are allowed.status: OrderStatususes it insideOrder. With'cancelled', the checker warns you.
interface and type can both describe an object, but only type can name a union. In this course, interface is for objects and type for everything else.
A shape can also be written without a name, right where it’s used: { productId: number; quantity: number } is “an object with those two pieces of data.” You’ll see it like that from lesson 4, “HTTP server” onward.
Functions with types, and the undefined you can’t forget
Section titled “Functions with types, and the undefined you can’t forget”The rest of the file is the data and two FunctionA named piece of code that takes some data, does something with it and returns a result. It’s written once and used as many times as needed.Go to definition, now with types, also exported:
export const products: Product[] = [ { id: 1, name: 'T-shirt', price: 20 }, { id: 2, name: 'Mug', price: 8.5 }, { id: 3, name: 'Hoodie', price: 35 },];
// Returns the product with that id, or undefined if there isn't one: the type makes you handle it.export function findProduct(id: number): Product | undefined { return products.find((product) => product.id === id);}
export function total(product: Product, quantity: number): number { return product.price * quantity;}Product[]is an ArrayA list of values in order, such as [20, 8.5, 35]. Each value is read by its position, which starts counting at 0: prices[0] is the first one.Go to definition of products: the square brackets say “a list of.”findProduct(id: number)only accepts a number.products.find(…)goes through the list and returns the first product that meets the condition: here, that itsidis the one you’re looking for. If none meets it, it returnsundefined, “no value.”: Product | undefined, after the parenthesis, is what the function returns: a product, orundefined.totalreceives a product and a quantity, and returns a number.
Using the types: the main program
Section titled “Using the types: the main program”src/main.ts creates an order and works out what it costs:
import { findProduct, total, type Order } from './products.ts';
const order: Order = { id: 1, productId: 2, quantity: 3, status: 'pending' };const product = findProduct(order.productId);
if (product === undefined) { console.log(`There's no product ${order.productId}`);} else { console.log( `Order ${order.id}: ${order.quantity} × ${product.name} = ${total(product, order.quantity)} €`, );}- The
importbrings in three pieces thatproducts.tsexports../means “in this same folder,” and the.tsextension is written out because Node looks for the file exactly as named.type Ordersignals thatOrderis only a type. const order: Orderforces the object to have the four pieces of data, with their types.producthas no annotation: TypeScript works out that it’sProduct | undefined. In VS Code, hover over it and it shows you.if (product === undefined)checks whether it wasn’t found. In theelse, TypeScript already knows it’s aProductand lets you readproduct.name: it has narrowed the type.
If you delete the if, the checker complains: 'product' is possibly 'undefined'. Without TypeScript, you’d find out when someone asked for a product that doesn’t exist: TypeError: Cannot read properties of undefined (reading 'name'). On a server, a 500 error.
unknown and any: what comes from outside
Section titled “unknown and any: what comes from outside”The end of main.ts receives a product in JSON, the way a client would send it in a request:
// What comes from outside (a JSON, a request) is unknown: you have to check it before using it.const data: unknown = JSON.parse('{"id":4,"name":"Cap","price":15}');if (typeof data === 'object' && data !== null && 'name' in data) { console.log(`A product has arrived: ${String(data.name)}`);}TypeScript can’t know what the text that JSON.parse reads will contain. For what you don’t know, there are two types:
| Type | What it means | What it lets you do |
|---|---|---|
any |
“Anything: don’t check a thing” | Everything, with no warnings: it switches TypeScript off for that data |
unknown |
“I don’t know what it is” | Nothing, until you check what it is |
JSON.parse returns any, and that’s why the code annotates data: unknown. The if condition checks the data in three steps, joined with && (“and”):
typeof data === 'object': it’s an object, not a number or a piece of text.data !== null: it isn’tnull, the “empty” value. This is needed because, due to a JavaScript quirk,typeof nullis also'object'.'name' in data: it has a piece of data calledname.
Inside the if, TypeScript now lets you use data.name, and String(…) turns it into text, whatever it is.
Node erases the types when it runs
Section titled “Node erases the types when it runs”Node 26, the course’s version, runs a .ts file with no options and no warnings. But it knows nothing about types: before running, it erases them. This example, examples/type-error.ts, has a mistake on purpose:
import type { Product } from '../src/products.ts';
// The price is text, not a number: tsc marks it as an error, but Node runs it anyway.const mug: Product = { id: 2, name: 'Mug', price: '8.5' };console.log(mug.price * 2);And this is what Node really runs, taken from stripTypeScriptTypes, its function for erasing types:
// The price is text, not a number: tsc marks it as an error, but Node runs it anyway.const mug = { id: 2, name: 'Mug', price: '8.5' };console.log(mug.price * 2);The import type line has been left blank (you can’t see it above, because it’s the first one) and the : Product turned into spaces. That way every line and every column stays in place, and an error points to the same spot in your file. What’s left is JavaScript, which doesn’t know the price was supposed to be a number.
- src/main.tsJavaScript with types
Node erases the types
- JavaScriptthe types, replaced with spaces
runs it as is
- The outputwithout checking any type
When it runs, no types are left. An order that arrives with "quantity": "lots" gets in anyway, even if your interface says number: the data in a request is checked when it’s received, with code. It’s the golden rule from Phase 0, “never trust the client,” and lesson 7, “Validation”, puts it into practice.
tsc –noEmit: the checker, separately
Section titled “tsc –noEmit: the checker, separately”What does the checking is tsc, the TypeScript compiler. Compiling is translating a program into another language, and tsc was born to translate .ts into .js. Here Node already erases the types, so you only use it to check:
tsc --noEmitchecks the whole project without writing any file (no emit). If everything is fine, it says nothing.- The editor does the same check while you type: VS Code underlines each error in red and, when you hover over it, tells you what’s wrong.
You’ll install TypeScript 7, which came out in July 2026: the same language, with the compiler rewritten in Go, another programming language. In Microsoft’s measurements, on large projects, it checks about ten times faster.
The tsconfig.json: the checker’s rules
Section titled “The tsconfig.json: the checker’s rules”tsc reads its rules from tsconfig.json, in the project folder:
{ // Only for checking the types (npm run check): Node runs the .ts files without compiling them. "compilerOptions": { "target": "esnext", "module": "nodenext", "strict": true, "noEmit": true, // Imports include the .ts extension, the way Node reads them. "allowImportingTsExtensions": true, // Only the part of TypeScript that Node can erase: no enum, for example. "erasableSyntaxOnly": true, "verbatimModuleSyntax": true, "skipLibCheck": true, "types": ["node"] }, // The examples have errors on purpose: they're checked separately. "exclude": ["examples", "node_modules"]}It’s JSON with one exception: it allows comments, the lines that start with //. What matters, piece by piece:
strict: trueturns on all the strict checks, like the one forundefined.noEmitis the--noEmit, already written here.allowImportingTsExtensionsacceptsimportlines with.ts.erasableSyntaxOnlywarns you if you use something Node can’t erase (the next section).verbatimModuleSyntaxrequirestypewhen you import a type: when it runs,Orderdoesn’t exist, and Node would fail looking for it.types: ["node"]loads Node’s types, from the@types/nodepackage.excludeleaves outexamples, which has mistakes on purpose.
The rest (target, module, skipLibCheck) says you’re aiming at the most modern JavaScript and at Node’s modules, and not to check the types of the installed packages.
What Node can’t erase
Section titled “What Node can’t erase”Almost all of TypeScript can be erased without changing what the program does. A few pieces can’t, because they generate code. The best known is enum, a list of named values that creates a real object. Node doesn’t accept them.
You don’t need them: a union of literal types, like OrderStatus, does the same and is erased without a trace.
Try it
Section titled “Try it”The goal: move the shop to TypeScript and see which mistakes the checker catches before anything runs. It all happens in your terminal, in ~/backend-course/phase-3/shop-api. If you get stuck, download this lesson’s folder and compare it with yours:
cd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/03-typescript.tar.gztar -xzf 03-typescript.tar.gzThe outputs are from Node 26.11.1. Your times will be different.
Set up the project
Section titled “Set up the project”1. Install TypeScript
npm install --save-dev typescript@7.0.2 @types/node@26.6.4What you will see:
added 4 packages, and audited 5 packages in 3s
found 0 vulnerabilitiesTwo Package (of code)Ready-to-use code that someone publishes with a name and a version number, so others can install it in their projects instead of writing it. In Node.js, packages are installed with npm and kept in the node_modules folder.Go to definition, with their exact version, as in lesson 1: typescript, which brings tsc, and @types/node, Node’s types. --save-dev records them as development dependencies: they’re needed to write the code, not to run it. The other two “packages” are their dependencies.
Now create tsconfig.json, src/products.ts and src/main.ts with what you’ve seen in “How it really works.” The code moves to the src/ folder (from source, “source code”), and the files from lesson 2 aren’t needed anymore: you can delete them.
2. Add the project's commands
npm pkg set scripts.start="node src/main.ts"npm pkg set scripts.test="node --test"npm pkg set scripts.check="tsc --noEmit"npm pkg get scriptsWhat you will see:
{"test": "node --test","start": "node src/main.ts","check": "tsc --noEmit"}npm pkg set changes package.json without opening it, as in lesson 1, and npm pkg get scripts shows you how they ended up. Three named commands: npm start runs the program, npm test runs the tests (you’ll use them from lesson 4) and npm run check checks the types. start and test are names npm knows; for any other, like check, you write npm run.
If one is missing, or comes out cut short, run its line again with the quotes: without them, the terminal splits node --test at the space. Your package.json will have a few more fields, from npm init -y; the one in the downloadable folder is this:
{ "name": "shop-api", "version": "1.0.0", "private": true, "type": "module", "engines": { "node": ">=24" }, "scripts": { "start": "node src/main.ts", "test": "node --test", "check": "tsc --noEmit" }, "devDependencies": { "@types/node": "26.6.4", "typescript": "7.0.2" }}3. Run the program
node src/main.tsWhat you will see:
Order 1: 3 × Mug = 25.5 €A product has arrived: CapNode runs the .ts file directly: no compiling first. npm start does the same.
If you get ERR_MODULE_NOT_FOUND, check that the import in main.ts ends in products.ts, with its extension.
4. Check the types
npx tsc --noEmitnpx runs a program installed in the project, here tsc. Nothing comes out: in the terminal, silence is a good sign. npm run check does the same.
Error 1: a status that doesn’t exist
Section titled “Error 1: a status that doesn’t exist”In src/main.ts, change 'pending' to 'cancelled' and save. If you have the folder open in VS Code, you’ll see the red underline before running anything. Now run it and check:
5. Node runs it, tsc catches it
node src/main.tsnpx tsc --noEmitWhat you will see:
Order 1: 3 × Mug = 25.5 €A product has arrived: Capsrc/main.ts:3:58 - error TS2322: Type '"cancelled"' is not assignable to type 'OrderStatus'.
3 const order: Order = { id: 1, productId: 2, quantity: 3, status: 'cancelled' }; ~~~~~~
src/products.ts:16:3 - The expected type comes from property 'status' which is declared here on type 'Order' 16 status: OrderStatus; ~~~~~~
Found 1 error in src/main.ts:3Node runs the program as if nothing were wrong. tsc doesn’t: 'cancelled' doesn’t fit in OrderStatus (“is not assignable”), and underneath it tells you where the rule comes from, the status field of Order.
3:58 is the line and the column: if your file has one line more or less, they change. Put 'pending' back.
Error 2: a price as text
Section titled “Error 2: a price as text”Create the examples folder with two files: type-error.ts, the one from “Node erases the types when it runs,” and its own tsconfig.json, which inherits the rules of the main one (extends) and only checks this folder:
{ "extends": "../tsconfig.json", "include": ["."], "exclude": []}6. The price of two mugs
node examples/type-error.tsnpx tsc -p examplesWhat you will see:
17examples/type-error.ts:4:44 - error TS2322: Type 'string' is not assignable to type 'number'.
4 const mug: Product = { id: 2, name: 'Mug', price: '8.5' }; ~~~~~
src/products.ts:6:3 - The expected type comes from property 'price' which is declared here on type 'Product' 6 price: number; ~~~~~
Found 1 error in examples/type-error.ts:417 is right by chance: with *, JavaScript turns the text into a number. With a +, as in “The problem,” you’d get 8.52. tsc doesn’t wait to see the result: text doesn’t fit where a number goes.
-p examples (from project) tells tsc which tsconfig.json to use: the one in the examples folder.
Error 3: an enum
Section titled “Error 3: an enum”Create src/status.ts with an enum, like the ones in many tutorials:
enum Status { Pending, Paid,}console.log(Status.Paid);7. What Node can't erase
node src/status.tsWhat you will see:
node:internal/modules/run_main:111 triggerUncaughtException( ^
file:///Users/ana/backend-course/phase-3/shop-api/src/status.ts:1> enum Status { Pending, Paid,> } console.log(Status.Paid);
SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript enum is not supported in strip-only mode at parseTypeScript (node:internal/modules/typescript:57:40) … at afterResolve (node:internal/modules/esm/loader:614:52) {code: 'ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX'}
Node.js v26.11.1This time Node does stop: enum isn’t supported in strip-only mode, the mode that only erases types. The lines with > point at the guilty piece. We’ve removed eight at … lines, which say where Node was passing through on the inside.
On Linux and WSL, the path starts with /home/ana.
8. tsc would have told you before
npx tsc --noEmitWhat you will see:
src/status.ts:1:6 - error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled.
1 enum Status { ~~~~~~
Found 1 error in src/status.ts:1The editor would have marked it while you were typing. Delete the file with rm src/status.ts, and npx tsc --noEmit goes back to silence.
Challenge: in src/main.ts, delete the if (typeof data …) line and its closing brace, }. What does npx tsc --noEmit say? And if you also change unknown to any?Show answer
With unknown, tsc doesn’t let you read data.name without first checking what it is:
src/main.ts:16:48 - error TS18046: 'data' is of type 'unknown'.
16 console.log(`A product has arrived: ${String(data.name)}`); ~~~~
Found 1 error in src/main.ts:16With any, silence: not because the code is right, but because you’ve switched the check off. If the JSON didn’t bring name, nobody would warn you. Leave main.ts as it was.
You have already seen it
Section titled “You have already seen it”- “Hello, undefined” or a total of “€NaN” in an email or on a website: a piece of data that was missing, or of another type, and nobody checked it.
- VS Code’s suggestions, even in
.jsfiles: under the hood, the editor uses TypeScript to know what each object has. - This very site. Every change to its code goes through an automatic type check before it’s published. So does every folder of the
shop-apiproject, withnpm run check.
Common mistakes
Section titled “Common mistakes”- Believing types are checked when the code runs. Node erases them. What arrives in a request has to be checked with code (lesson 7, “Validation”).
- Using
anyto make the checker shut up. The warning goes away, not the mistake. For what you don’t know, useunknown, and check it. - Copying an
enumfrom a tutorial. Node answersERR_UNSUPPORTED_TYPESCRIPT_SYNTAX. Use a union:'pending' | 'paid'. - Importing without
.tsor withouttype. Without the extension, Node givesERR_MODULE_NOT_FOUND. Withouttype,does not provide an export named 'Order': when it runs, that type no longer exists.
Summary
Section titled “Summary”- A type says what kind of data goes where. You annotate it with
:, name it withinterfaceortype, and a union of literals ('pending' | 'paid') limits the possible values. Product | undefinedforces you to count on something not existing, andunknownforces you to check what comes from outside.anyswitches the check off.- Node runs
.tsfiles by erasing the types: it doesn’t compile or check anything, and it only accepts syntax that can be erased. - What does the checking is
tsc --noEmit, and your editor while you type. When the code runs, no types are left: the data in a request is validated with code.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- TypeScript for the New Programmer (official documentation): TypeScript for people who are just starting to program.
- Everyday Types (official documentation): everyday types, unions and literal types included.
- Modules: TypeScript (Node.js): how Node runs
.tsfiles and which syntax it doesn’t accept. - erasableSyntaxOnly (official documentation): the rule that warns you about what Node can’t erase.
- A 10x Faster TypeScript (Microsoft): the announcement of the compiler rewritten in Go.