On this page

Hands-On Exercise: Add TypeScript to a Small Node Project

Updated on July 27, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

This exercise takes a small Node.js project written in plain JavaScript and converts it into TypeScript, one step at a time. Every command and every code change below is given exactly as it should be typed — the goal is to build the working project by following along precisely, not to guess at the solution. By the end, the project reads a JSON config file, has a typed helper module, and demonstrates TypeScript catching three real mistakes before the code ever runs.


Setting Up the Plain Node Project​

Start by creating a new project folder and initializing it:


mkdir node-ts-demo

cd node-ts-demo

npm init -y

Create the entry file index.js at the root of the project:


const fs = require("fs");

const path = require("path");



function loadConfig() {

  const filePath = path.join(__dirname, "config.json");

  const raw = fs.readFileSync(filePath, "utf8");

  return JSON.parse(raw);

}



const config = loadConfig();

console.log("Config loaded:", config);

Alongside it, create config.json:


{

  "version": "1.0.0",

  "debug": true

}

Run it to confirm it works before any TypeScript is involved:


node index.js

The output should show the parsed config object logged to the console. At this stage config is typed as nothing at all — it's plain JavaScript, so there's no autocomplete on config.version, and no warning if the code later tries to read a field that doesn't exist. That gap is exactly what the rest of this exercise closes.


Installing TypeScript and Node Types​

Install TypeScript itself along with the type definitions for Node's built-in modules:


npm install --save-dev typescript @types/node

@types/node is what teaches TypeScript the shapes of fs, path, and the rest of Node's core API — without it, TypeScript would have no idea what fs.readFileSync even returns.

Generate a starting configuration file:


npx tsc --init

This creates tsconfig.json in the project root.


Configuring tsconfig.json for Node​

Open tsconfig.json and replace its contents with the essentials this project needs:


{

  "compilerOptions": {

    "target": "ES2020",

    "module": "CommonJS",

    "rootDir": "./src",

    "outDir": "./dist",

    "strict": true,

    "esModuleInterop": true

  },

  "include": ["src"]

}

rootDir and outDir tell TypeScript where source files live and where compiled JavaScript should be written, strict turns on the full set of strictness checks (including the null-safety behavior relied on later), and esModuleInterop allows import-style syntax to work cleanly against Node's CommonJS modules.

Create the src folder that rootDir points to, and move the entry file into it:


mkdir src

Move index.js into src/index.js. Leave config.json exactly where it is, at the project root — this matters, and the reason comes up in the next step.


Converting the Entry File to TypeScript​

Rename the file so TypeScript starts analyzing it:


src/index.js → src/index.ts

Nothing else changes yet. From this point on, TypeScript will report errors on this file the moment something doesn't type-check.


Typing the Node Imports​

Replace the require() calls with import statements:


import fs from "fs";

import path from "path";

TypeScript resolves the types for both modules automatically through @types/node — no extra configuration needed. This still compiles down to ordinary CommonJS require() calls under the hood (that's what esModuleInterop enables); it does not turn the project into a native ES module, so nothing needs to change in package.json.

This is also the point where the earlier warning becomes relevant. index.ts now lives in src/, and once compiled, its output will live in dist/. In both cases, __dirname points to that file's own folder — src/ or dist/ — not the project root where config.json actually is. The original path construction,


const filePath = path.join(__dirname, "config.json");

would now look for config.json inside src/ or dist/, where it doesn't exist. Since config.json sits one level above both of those folders, the fix is to go up one directory before joining the filename:


const filePath = path.join(__dirname, "..", "config.json");

This one-line change is folded into the function as it's typed in the next step.


Typing the loadConfig Function​

Right now, JSON.parse returns any, which means config.version and config.debug have no real type. Define a type describing the expected shape of the config file:


type AppConfig = {

  version: string;

  debug: boolean;

};

Then update loadConfig to use both the corrected path and the new type:


function loadConfig(): AppConfig {

  const filePath = path.join(__dirname, "..", "config.json");

  const raw = fs.readFileSync(filePath, "utf8");

  return JSON.parse(raw) as AppConfig;

}

as AppConfig is a type assertion, not a verification — it tells TypeScript to treat the parsed result as an AppConfig without actually checking that the JSON file's contents match that shape at runtime. That's an intentional simplification for this exercise; the practical effect is that config.version and config.debug now have real types for every line of code that comes after, and accessing a field that doesn't exist on AppConfig (like config.author) is now a compile-time error rather than undefined discovered later.


Adding Error Handling​

Make the function safer by checking that the file exists before trying to read it:


function loadConfig(): AppConfig {

  const filePath = path.join(__dirname, "..", "config.json");



  if (!fs.existsSync(filePath)) {

    throw new Error("Config file not found");

  }



  const raw = fs.readFileSync(filePath, "utf8");

  const parsed = JSON.parse(raw);

  return parsed as AppConfig;

}

fs.existsSync returns a plain boolean, and fs.readFileSync returns a string here because an encoding was passed — both typed automatically by @types/node. The as AppConfig assertion on the last line still isn't a runtime guarantee that parsed truly matches AppConfig; what this step adds is a check that the file exists at all, which prevents a confusing low-level file-system error from surfacing if config.json is ever missing or misplaced.


Compiling and Running the Project​

Compile the TypeScript source:


npx tsc

This produces dist/index.js. Run the compiled output:


node dist/index.js

The same "Config loaded:" output from the very first run should appear. This works — without needing to copy config.json anywhere — specifically because the path was corrected earlier to go up one directory from __dirname, landing back at the project root regardless of whether the code runs from src/ or from the compiled dist/ folder.


Adding a Second Typed File​

Create a small helper module at src/logger.ts:


export function log(message: string): void {

  console.log(`[LOG] ${message}`);

}

In src/index.ts, import it at the top of the file alongside the existing imports:


import { log } from "./logger";

Then, directly below the existing const config = loadConfig(); line, add a call to it:


log(`Loaded version ${config.version}`);

log only accepts a string, and config.version is already typed as string from AppConfig, so this line type-checks without any extra work. Recompile and run again (npx tsc followed by node dist/index.js) to see the new log line appear.


Confirming TypeScript Catches Mistakes​

With everything wired up, deliberately introducing each of the following lines into src/index.ts and running npx tsc shows TypeScript rejecting all three before any code executes:


config.version = 123; // ❌ Type 'number' is not assignable to type 'string'

log(42); // ❌ Argument of type 'number' is not assignable to parameter of type 'string'

fs.readFileSync(10, "utf8"); // ❌ Argument of type 'number' is not assignable to parameter of type 'PathLike'

Each of these compiles fine in the original plain-JavaScript version of this project and would only fail — or silently misbehave — once the code actually ran. Remove them after confirming the errors, and the project compiles cleanly again.

Key Takeaways​

This exercise walked a small Node project through the same conversion path most real teams follow: install TypeScript and @types/node, configure rootDir/outDir to separate source from compiled output, then migrate one file at a time rather than all at once. Moving the entry file into src/ changed what __dirname resolves to, which is why the path to config.json needed adjusting — a detail that's easy to miss and would otherwise surface as a confusing "file not found" error only after compiling. Typing the parsed JSON with AppConfig and an explicit assertion gave every later line of code real autocomplete and error-checking, with the caveat that the assertion itself is not a runtime guarantee. The final check — deliberately breaking three lines and watching TypeScript reject each one — is the concrete payoff: the same mistakes that would have failed silently or crashed at runtime in the plain JavaScript version are now caught before the code ever executes.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Working with Node.js

Next

Narrowing, Guards & Control Flow Analysis