Until today, every program in this course has been one file in its own day folder, with values typed straight into the code. Real programs are different in three ways: they are split across several files, they come with a few settings files so that anyone can install and run them, and they read their input from outside the code. Today covers all three. Make a new day13 folder and set it up the way Day 1 showed (npm init -y, npm install --save-dev typescript, and the starter tsconfig.json); by the end of today you will have changed each of those files on purpose and know why.
13.1 Modules: One File, One Job
The Day 12 grade book is close to 100 lines in one file. To find the letter-grade rule you scroll past the student data, the averaging code, and the report printing. If a second program, say a report card printer, needs the same average function, the only way to get it so far is to copy and paste it, and then a fix to one copy does not reach the other. Programmers solve both problems the same way: they put each job in its own file and let files share code with each other.
In TypeScript (and modern JavaScript) every file is a module: a file of code with its own private set of names. A const or a function declared in one module cannot be seen from another module unless the first module chooses to share it and the second asks for it. That gives two new keywords:
| Keyword | Where it goes | What it means |
|---|---|---|
export |
In front of a declaration | “Other files may use this name.” |
import |
At the top of the file that needs it | “Bring these names in from that file so I can use them.” |
Here is a tip calculator split in two. money.ts holds two money functions and shares both by writing export in front of each function:
export function tipFor(bill: number, percent: number): number {
return (bill * percent) / 100;
}
export function formatDollars(amount: number): string {
return `$${amount.toFixed(2)}`;
}main.ts is the file you run. Its first line is an import declaration that asks for both functions by name:
import { formatDollars, tipFor } from "./money.ts";
const bill = 48;
const tip = tipFor(bill, 20);
console.log(`Tip: ${formatDollars(tip)}`);
console.log(`Total: ${formatDollars(bill + tip)}`);Run the check, then run main.ts (you never run money.ts yourself):
npx tsc
node main.ts
Tip: $9.60
Total: $57.60
If node main.ts instead stops with SyntaxError: Cannot use import statement outside a module, open package.json, change "type": "commonjs" to "type": "module", save, and run it again. 13.4 explains that line.
Take line 1 of main.ts apart piece by piece:
| Piece | What it is |
|---|---|
import |
Starts an import declaration; imports go at the very top of a file |
{ formatDollars, tipFor } |
The names to bring in, in braces, separated by commas; each must be a name the other file exports |
from |
Separates the names from where they come from |
"./money.ts" |
The module path: ./ means “in the same folder as this file,” and money.ts is the file’s full name |
The names you list are called named imports, and the exports they match are named exports: the two sides are joined by spelling, so tipFor in the braces must be spelled exactly as the export function tipFor in money.ts. The order inside the braces does not matter; this course lists them in alphabetical order so they are easy to scan.
Why must the path start with ./? A path with no ./ (such as "money.ts") means something else: “a package called money.ts, installed in node_modules.” (13.10 shows a third kind of path, for modules that come with Node.) The ./ says “my own file, right here.” And why must it end in .ts? Node finds files by their exact name and never guesses an ending, and Node runs your .ts files directly, so the file it must load is literally money.ts. Day 1’s tsconfig.json included "allowImportingTsExtensions": true precisely so that the checker accepts that .ts ending.
Key idea
A module is one file. export in front of a declaration shares it; import { name } from "./file.ts"; at the top of another file brings it in by its exact name, with ./ for “this folder” and the full .ts file name.
When npx tsc checks main.ts, it follows the import into money.ts and reads the types there, so a call such as tipFor("48", 20) in main.ts is still a type error: types cross the file boundary along with the functions. That is the big difference from copy and paste: there is one tipFor, and every file that imports it uses the same one, checked the same way.
Watch out
Leaving out the .ts ending. Writing the path the way you might write it in everyday speech, "./money", is the most common import mistake:
import { formatDollars, tipFor } from "./money";
console.log(formatDollars(tipFor(48, 20)));main.ts:1:39 - error TS2835: Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Did you mean './money.js'?A relative import path is one that starts with ./ (or ../, “the folder above”), and the checker is following Node’s rules, which require the full file name. Notice that the message suggests ./money.js: that is the spelling for projects that convert their .ts files to .js files before running them. This course runs .ts files directly, so the fix is "./money.ts". If you skip the check and run the broken file anyway, Node stops with Error [ERR_MODULE_NOT_FOUND]: Cannot find module, because there is no file named exactly money.
Pause and try
Question 1 · Multiple choice
money.ts is the file shown above, and main.ts is in the same folder. Which first line for main.ts lets it call tipFor?
import { tipFor } from "./money.ts";import { tipfor } from "./money.ts";import { tipFor } from "money.ts";export { tipFor } from "./money.ts";
Check your reasoning
A. Named imports go in braces, spelled exactly as exported, and a file in the same folder is reached with ./ and its full name.
- B is wrong: names are matched by spelling, including capitals.
money.tsexportstipFor, nottipfor, so the checker reports that there is no such export. - C is wrong: without
./, the path names a package innode_modules, and there is no package calledmoney.ts. - D is wrong:
exportshares a name from the file it is written in; it does not bring anything intomain.ts, sotipForwould still be unknown there.
Reread 13.1 Modules: One File, One Job if you chose differently.
Question 2 · Short answer
Priya deletes the word export from line 5 of money.ts but leaves main.ts alone. Which file does npx tsc complain about, and why there?
Check your reasoning
Model answer: It complains about main.ts, on line 1. money.ts is still a correct file on its own: formatDollars is now a private function of that module, which is allowed. The problem is that main.ts asks for a name that money.ts no longer shares, and the import is in main.ts.
A complete answer must:
- name
main.ts(the importing file), and - explain that without
export,formatDollarsis private tomoney.ts, so the import asks for something that is not shared.
Reread 13.1 Modules: One File, One Job if your answer differed. 13.2 shows the exact message.
13.2 What Importing Runs, and What Stays Private
Splitting a program raises two questions a single file never did. When main.ts imports from another file, does the other file’s code run? And if a module has a helper function that only it should use, how do you keep other files from depending on it?
Private helpers and exported constants
You can export any declaration, not only functions. Here grades.ts exports a constant and a function, and keeps a helper to itself:
export const PASS_MARK = 60;
export function average(scores: number[]): number {
if (scores.length === 0) {
return 0;
}
return total(scores) / scores.length;
}
function total(scores: number[]): number {
return scores.reduce((sum, score) => sum + score, 0);
}import { average, PASS_MARK } from "./grades.ts";
const scores = [72, 55, 64];
const avg = average(scores);
console.log(`Average: ${avg.toFixed(1)}`);
console.log(avg >= PASS_MARK ? "Passing" : "Not passing yet");Average: 63.7
Passing
Walk through it:
| Line(s) | What happens |
|---|---|
| grades.ts 1 | export const PASS_MARK = 60; shares a constant. Importing it does not let main.ts change it: it is still a const |
| grades.ts 3–8 | average is exported. It calls total, which is fine: code inside a module can use every name in that module, exported or not |
| grades.ts 10 | total has no export, so it is private to grades.ts: usable inside the file, invisible outside it |
| main.ts 1 | Brings in average and PASS_MARK. total is not asked for, and could not be |
| main.ts 4–6 | (72 + 55 + 64) / 3 is 63.666…, shown as 63.7; it is at least 60, so Passing |
Notice average on line 7 of grades.ts can call total, which is declared further down on line 10. A function declaration can be called from anywhere in its own file, and by the time average actually runs (from main.ts), the whole of grades.ts has been read.
Keeping helpers private is a feature, not a limitation. The exported names are the module’s promise to other files, its public interface; everything else may be renamed, rewritten, or deleted without breaking anyone. If main.ts could call total, you would have to keep total working forever.
Watch out
Importing a name that is not exported. Ask for total and the checker refuses:
import { average, total } from "./grades.ts";
const scores = [72, 55, 64];
console.log(total(scores), average(scores));main.ts:1:19 - error TS2459: Module '"./grades.ts"' declares 'total' locally, but it is not exported.“Declares locally” means the name exists inside grades.ts, and column 19 points at total in the braces. Either add export in front of function total (if other files really should use it), or stop importing it. If you skip the check and run it, Node stops before printing anything, with SyntaxError: The requested module './grades.ts' does not provide an export named 'total'.
An imported module runs first, and only once
A module is not only a bag of functions: any statement at its top level, such as a console.log, is code that runs. Here is a module that announces itself:
Worked example: Which file runs first?
console.log("prices.ts runs");
export const prices = [3, 5, 2];import { prices } from "./prices.ts";
console.log("main.ts runs");
console.log(prices.length);node main.ts shows:
prices.ts runs
main.ts runs
3Step by step:
- Node reads
main.tsand sees theimporton line 1 before running anything. - It loads
prices.tsand runs it from top to bottom: line 1 logsprices.ts runs, line 3 creates thepricesarray and makes it available. - Only then does
main.tsrun its own statements: line 3 logsmain.ts runs, and line 4 logs the length of the imported array,3.
Imports are handled before the importing file’s own code, even though main.ts is the file you ran. That is what makes prices ready to use on line 4. If two files import the same module, it still runs only once: Node remembers every module it has loaded and hands the same exports to every file that asks. Review question 20 traces that case.
This is also why modules usually do not print anything at their top level. A module whose job is to provide functions should just declare them; the printing belongs in the file you run, which programmers call the entry point (here main.ts).
Key idea
A module shares only what it exports; everything else is private to its file. When a file is imported, its top-level code runs once, before the code of the file that imported it.
Pause and try
Question 3 · Tracing
Predict exactly what node main.ts shows.
console.log("greeting.ts starts");
export const greeting = "Hello";
console.log("greeting.ts ends");import { greeting } from "./greeting.ts";
console.log("main.ts starts");
console.log(`${greeting}, Ana`);Check your reasoning
greeting.ts starts
greeting.ts ends
main.ts starts
Hello, AnaThe import on line 1 of main.ts is handled first, so all of greeting.ts runs from top to bottom: its line 1, then the export const (which logs nothing), then its line 5. Only then does main.ts run its line 3 and line 4. Putting the export in the middle of greeting.ts changes nothing about the order: a module always finishes running before the file that imported it starts.
Reread 13.2 What Importing Runs, and What Stays Private if your order differed.
Question 4 · Multiple choice
With grade-module/grades.ts as shown above, which line, written at the top of another file in the same folder, does npx tsc reject?
import { PASS_MARK } from "./grades.ts";import { average, PASS_MARK } from "./grades.ts";import { average, total } from "./grades.ts";import { average } from "./grades.ts";
Check your reasoning
C. total has no export in front of it, so it is private to grades.ts, and the checker reports TS2459: … declares 'total' locally, but it is not exported.
- A and D are fine: a file may import just some of the exported names.
- B is fine: both names are exported, and order in the braces does not matter.
Reread 13.2 What Importing Runs, and What Stays Private if you chose differently.
13.3 Exporting and Importing Types
The grade book’s Student type is needed in both files: grades.ts uses it in classAverage’s parameter, and the main file uses it for the array of students. A type alias can be exported like anything else, by writing export in front of type:
export type Book = { title: string; pages: number };
export function describe(book: Book): string {
return `${book.title} (${book.pages} pages)`;
}Importing it needs one extra word, and the reason goes back to Day 1. Node runs a .ts file by type stripping: it deletes the types and runs what is left, without checking them. When Node sees import { Book, describe }, it cannot tell that Book is only a type, so it keeps the whole import and then looks for a real value called Book in books.ts. There is none, because Node stripped export type Book … out of books.ts too.
Watch out
Importing a type as if it were a value. This program passes npx tsc with no errors:
import { Book, describe } from "./books.ts";
const novel: Book = { title: "Holes", pages: 233 };
console.log(describe(novel));But node main.ts stops before printing anything:
SyntaxError: The requested module './books.ts' does not provide an export named 'Book'The checker is happy, because Book is exported. The crash happens when Node runs the stripped file. This is a rare case where a clean npx tsc and a crash go together, so remember the rule below.
The fix is to mark the type with the word type inside the braces. Node then strips type Book along with every other type, and keeps only describe:
import { type Book, describe } from "./books.ts";
const novel: Book = { title: "Holes", pages: 233 };
console.log(describe(novel));Holes (233 pages)
When every name you import is a type, you can put the word once, in front of the braces: import type { Book } from "./books.ts";. Both forms are called type-only imports.
Key idea
Export a type with export type. Import it with the word type in front of it, as in import { type Book, describe }, so that Node strips it like any other type annotation.
Pause and try
Question 5 · Multiple choice
shapes.ts contains export type Point = { x: number; y: number }; and export function distance(a: Point, b: Point): number { … }. Which import lets main.ts use both names and run with node main.ts?
import { Point, distance } from "./shapes.ts";import { type Point, distance } from "./shapes.ts";import type { Point, distance } from "./shapes.ts";import { Point, type distance } from "./shapes.ts";
Check your reasoning
B. Point is only a type, so it is marked type and stripped; distance is a real function, so it stays in the import and Node loads it.
- A is wrong:
npx tscaccepts it, but Node keepsPointin the import and crashes withdoes not provide an export named 'Point'. - C is wrong:
typein front of the braces makes every name type-only, sodistancecould not be called; the checker reports that it cannot be used as a value. - D is wrong: it marks the wrong name.
distancewould be stripped (so it cannot be called), andPointwould stay in the import and crash Node.
Reread 13.3 Exporting and Importing Types if you chose differently.
13.4 package.json and the Module Type
In 13.1 you may have had to change one line of package.json before the tip calculator would run. npx tsc was happy either way; the problem was in a file you had not opened since Day 1.
package.json describes the project to npm and to Node. npm init -y writes something like this (the first line takes its name from your folder):
{
"name": "day13",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs"
}
It is written in JSON (JavaScript Object Notation), the same format as tsconfig.json: an object literal where every key is in double quotes and there are no comments and no trailing commas. Most of the fields are labels for people who publish packages (description, keywords, author, license), and you can ignore them. Two matter today: "scripts" (13.5) and "type".
JavaScript has two module systems. The one you learned in 13.1, with import and export, is the modern standard, called ES modules (ES is short for ECMAScript, the official name of the JavaScript language). Node is older than that standard, so it also has its own older system, CommonJS, which shares code a different way. The "type" field tells Node which system the project’s files use:
"type" |
Node treats each .ts and .js file as… |
import and export |
|---|---|---|
"module" |
an ES module | Work |
"commonjs" |
a CommonJS file | Crash with a runtime error |
| (left out) | Node guesses from each file’s code | Work, after a warning asking you to add the field |
Recent versions of npm write "type": "commonjs", and with that setting the tip calculator stops on line 1 of main.ts:
SyntaxError: Cannot use import statement outside a module
Above that line Node prints a warning with the fix: Make sure to set "type": "module" in the nearest package.json file. So in every project from today on, change that line of package.json to:
"type": "module"
and node main.ts works. (If your package.json has no "type" line at all, add one; without it Node runs the file, but only after printing a warning that it had to guess.)
Notice who caught this: not npx tsc, which accepted the import, but Node, at run time. The checker’s job is types; whether Node can load the file is decided by package.json. That is worth remembering whenever a program passes the check and still will not start.
Key idea
package.json describes the project. Set "type": "module" in it so Node treats your files as ES modules; with
"commonjs", the first import stops the program with Cannot use import statement outside a module.
Watch out
Breaking the JSON. package.json must be valid JSON, and npm stops with an error if it is not. The usual slips are a missing comma between two fields, a comma after the last field, and single quotes instead of double quotes. When you add a line, check the line above it: every field except the last ends with a comma.
Pause and try
Question 6 · Short answer
Kai’s two-file program passes npx tsc, but node main.ts shows SyntaxError: Cannot use import statement outside a module, pointing at line 1. What should Kai look at, what should Kai change, and why did the type checker not catch it?
Check your reasoning
Model answer: Kai should open package.json and look at the "type" field. It is "commonjs" (or Kai’s npm wrote that by default), so Node treats main.ts as a CommonJS file, where import is not allowed. Changing it to "type": "module" makes Node treat the files as ES modules. The type checker did not catch it because its job is to check types, and the import is correct TypeScript; how Node loads the file is decided by package.json when the program runs.
A complete answer must:
- point to the
"type"field inpackage.jsonand the change to"module", and - explain that this is a runtime problem with how Node loads files, not a type error.
Reread 13.4 package.json and the Module Type if your answer differed.
13.5 Scripts and npm run
Every day so far you have typed two commands: npx tsc, then node with the right file name. Someone who downloads your project does not know which file is the entry point, or that they should check it first. A project can write its commands down for everyone, in the "scripts" field of package.json.
A script is a named terminal command stored in package.json. Replace the "scripts" object that npm init -y wrote with this one:
"scripts": {
"check": "tsc",
"start": "node main.ts"
},
Each entry is a name and the command it stands for. You run a script with npm run and its name:
npm run check
> day13@1.0.0 check
> tsc
npm first prints two lines starting with >: the project’s name and version from package.json, the script’s name, and the exact command it is about to run. Then the command runs. Here tsc printed nothing, which, as always, means no type errors. Notice the script says tsc, not npx tsc: inside a script, npm already looks in the project’s node_modules for tools, which is the job npx does on the command line.
start is special: npm start is a shortcut for npm run start (and npm test for npm run test). Run the tip calculator:
npm start
> day13@1.0.0 start
> node main.ts
Tip: $9.60
Total: $57.60
Now anyone who opens the project can read the two scripts and know how to check and start it, without knowing which file is which.
To pass extra words to the program, put them after -- (two hyphens), which means “the rest is for the script, not for npm.” npm adds them to the end of the command:
npm start -- notes.txt
> day13@1.0.0 start
> node main.ts notes.txt
Tip: $9.60
Total: $57.60
The tip calculator ignores the extra word, but the > line shows exactly what ran, which makes it easy to check. You will use extra words like this in 13.9.
Key idea
The "scripts" field names the project’s commands. npm run check runs tsc; npm start runs the start script;
words after -- are added to the end of the script’s command.
Watch out
Asking for a script that does not exist. A typo such as npm run chek does not run anything. npm answers npm error Missing script: "chek", and when the name is close to a real one, adds Did you mean this? with the right command. The same happens if you type npm test while the "test" script is gone, or if you edited package.json but forgot to save it. npm run with no name lists every script the project has.
Pause and try
Question 7 · Tracing
A project’s package.json has these scripts:
"scripts": {
"check": "tsc",
"start": "node main.ts",
"report": "node report.ts"
},For each command, write the command that npm actually runs (the second > line), or say what goes wrong: (a) npm start, (b) npm run report -- march.txt, (c) npm run reprot.
Check your reasoning
- (a)
node main.ts:npm startis the shortcut fornpm run start. - (b)
node report.ts march.txt: the words after--are added to the end of thereportcommand. - (c) Nothing runs. npm reports
Missing script: "reprot"and suggestsnpm run report.
Reread 13.5 Scripts and npm run if any line differed.
Question 8 · Multiple choice
Why does the check script say "tsc" and not "npx tsc"?
- Scripts cannot contain the word
npx. - npm runs scripts with the project’s
node_modulestools already available, sotscis found withoutnpx. tscandnpx tscare different programs.- Scripts only run Node, never other tools.
Check your reasoning
B. Inside a script, npm makes the project’s installed tools available by name, which is exactly what npx does on the command line. ("npx tsc" would also work; it is just longer.)
- A is wrong: a script may contain any command;
npx tscwould work, only more slowly. - C is wrong: both run the same type checker from
node_modules. - D is wrong: the
checkscript runstsc, which is not Node’s own command.
Reread 13.5 Scripts and npm run if you chose differently.
13.6 tsconfig.json Settings That Matter
On Day 1 you typed tsconfig.json without needing to understand it. Now that a project has several files and settings that interact, four of its settings are worth knowing properly. Here is the file again:
{
"compilerOptions": {
"strict": true,
"noEmit": true,
"target": "ES2024",
"module": "nodenext",
"erasableSyntaxOnly": true,
"allowImportingTsExtensions": true
}
}
"compilerOptions" holds the settings for tsc. With no file named on the command line, tsc looks for a tsconfig.json in the current folder and checks every .ts file in that folder and the folders inside it (it skips node_modules).
strict
"strict": true turns on strict mode, the full set of checks. Without it, the checker lets through many mistakes this course relies on it to catch. One example: in strict mode every parameter needs a type, either written or worked out from context.
function double(value) {
return value * 2;
}
console.log(double(21));implicit-any.ts:1:17 - error TS7006: Parameter 'value' implicitly has an 'any' type.
any is TypeScript’s “anything goes” type: the checker allows every operation on an any value, so it checks nothing about it. Without strict mode, value silently becomes any, and double("21") would pass the check (and show 42, because * converts the text to a number). Strict mode is also what makes the checker track null and undefined, so that a result such as find’s T | undefined must be checked before use (Days 9 and 11); without it, those checks disappear. Keep strict on in every project. Fix this example by writing value: number, or delete the file.
module
"module": "nodenext" tells the checker to treat files the way current Node does. Two consequences you have met today:
- It reads
"type"inpackage.jsonto decide how each file is loaded, just as Node does. - It requires the full file name in a relative import, which is why
"./money"gave TS2835 in 13.1.
target
"target": "ES2024" names the version of JavaScript your code is written for. JavaScript gains new built-in features every year; toSorted from Day 11, for example, arrived in 2023. The target tells the checker which built-in features exist, so with ES2024 it knows about everything this course uses. Node 24 runs all of them.
noEmit
"noEmit": true means “check only.” tsc stands for TypeScript compiler, and a compiler turns code into another form: without this setting, tsc would write a .js file next to every .ts file, with the types removed. You do not need those files, because Node strips the types itself when it runs a .ts file, so noEmit keeps your folder clean.
The last two settings make sure the checker matches what Node can run: "erasableSyntaxOnly" allows only TypeScript features that Node can handle by deleting the types, and "allowImportingTsExtensions" allows the .ts ending in import paths. You will add one more setting in 13.8.
| Setting | Short version | If it were missing or changed |
|---|---|---|
"strict": true |
Full checking | Untyped parameters become any; many null checks disappear |
"module": "nodenext" |
Follow Node’s rules for files and imports | The checker could accept imports that Node then cannot load |
"target": "ES2024" |
Expect this year’s JavaScript features | Newer built-ins such as toSorted would be reported as missing |
"noEmit": true |
Check only, write no files | tsc writes a .js file next to every .ts file |
Key idea
strict turns on full checking, module makes the checker follow Node’s rules, target says which JavaScript
features exist, and noEmit means “check only, write nothing.”
Watch out
Turning off strict to make an error go away. When a message is hard to understand, setting "strict": false makes it disappear, and the mistake is still there, now hidden. The checker is only useful if it is allowed to check. Read the message instead (Day 1 showed how), or fix the one line.
Pause and try
Question 9 · Multiple choice
Sam’s project folder fills up with .js files every time Sam runs npx tsc. Which setting is missing from Sam’s tsconfig.json?
"strict": true"noEmit": true"target": "ES2024""module": "nodenext"
Check your reasoning
B. Without noEmit, tsc acts as a compiler and writes a .js copy of every .ts file. "noEmit": true makes it check only.
- A is wrong:
strictdecides how much is checked, not whether files are written. - C is wrong:
targetdecides which JavaScript features the checker expects (and which version of JavaScript files would be written in), not whether they are written. - D is wrong:
moduledecides how files and imports are understood, not whether output is written.
Reread 13.6 tsconfig.json Settings That Matter if you chose differently.
13.7 Installing Packages
A package, as Day 1 said, is ready-made code someone has published for others to use, and npm downloads packages from a huge public collection called the npm registry. You have installed exactly one so far, typescript. Today you need a second, and before installing it, it is worth understanding what npm install records.
dependencies and devDependencies
Open package.json after Day 1’s install and you will find a new field at the bottom:
"devDependencies": {
"typescript": "^x.y.z"
}
npm writes the version it installed where this page shows x.y.z; the ^ means “this version or any later one that is compatible with it.” A package your project relies on is a dependency, and npm sorts them into two lists:
| Field | Installed with | For packages that… | Example |
|---|---|---|---|
"dependencies" |
npm install package-name |
Your program uses while it runs, so it must be there to start | A library your code imports and calls |
"devDependencies" |
npm install --save-dev package-name |
Only help you while developing: checking, testing, building | typescript |
The difference matters because the program never needs a development tool to run: node main.ts does not touch typescript at all. Keeping the two lists apart tells anyone reading package.json which packages the program itself needs. Every package this course installs (the type checker today, and later the tools you use to build and test web pages) is a development tool, so you will always use --save-dev.
node_modules and package-lock.json
npm install downloads each package into the node_modules folder, along with any packages it relies on in turn, and writes package-lock.json, the exact version of every single package it installed. node_modules can grow to thousands of files, and you never edit it.
You also never need to copy it. Typing npm install on its own, with no package name, reads package.json and package-lock.json and installs every package they list. So a project is shared without node_modules, and whoever receives it runs npm install once:
npm install
npm run check
npm start
Those three commands are the whole “how to run this project” for anyone, including you on a different computer.
.gitignore
Programmers save the history of their projects with Git, a version-control tool that records every change, and usually share projects through a Git website. A file named .gitignore in the project folder lists files and folders Git should leave out. (The name starts with a dot, and there is nothing before it.) Every Node project’s .gitignore contains at least this line:
node_modules/
The trailing / means “a folder with this name.” Leaving node_modules out keeps the shared project small, and nothing is lost, because npm install rebuilds it. package.json and package-lock.json must not be ignored: they are the list npm install rebuilds from. Even if you share a project as a zip file instead of with Git, follow the same rule and leave node_modules out.
Key idea
npm install name adds a package to "dependencies"; with --save-dev it goes in "devDependencies". Packages land
in node_modules, which you never edit or share: list it in .gitignore, and rebuild it with npm install.
Watch out
Deleting package-lock.json or editing node_modules to fix a problem. Both are managed by npm. If installed packages seem broken, delete the node_modules folder and run npm install again: npm rebuilds it exactly from the lock file. Keep package-lock.json; it is what makes the rebuild exact.
Pause and try
Question 10 · Multiple choice
Which of these belongs in "devDependencies" rather than "dependencies"?
- A package your program imports to format dates in its output
- The type checker,
typescript - A package your program imports to read spreadsheet files while it runs
- None: every package belongs in
"dependencies"
Check your reasoning
B. The type checker is used only while you develop: node main.ts never touches it.
- A and C are wrong: the program imports and calls those packages while it runs, so they are
"dependencies". Without them the program cannot start. - D is wrong: the two lists exist precisely so that development tools are kept apart from what the program needs.
Reread 13.7 Installing Packages if you chose differently.
Question 11 · Short answer
Ana sends Lee her project as a zip file: main.ts, grades.ts, package.json, package-lock.json, tsconfig.json, and .gitignore, but no node_modules. Lee types npm run check and gets an error that tsc is not found. Is Ana’s project broken? What should Lee do?
Check your reasoning
Model answer: The project is not broken; leaving node_modules out is the right way to share. Lee has not installed the packages yet, so the tsc tool does not exist on Lee’s computer. Lee should run npm install once (it reads package.json and package-lock.json and rebuilds node_modules), then npm run check and npm start.
A complete answer must:
- say that leaving out
node_modulesis correct, and - give
npm install(with no package name) as the step Lee missed, and say what it does.
Reread 13.7 Installing Packages if your answer differed.
13.8 Type Definitions for Node
So far your programs have used only what the JavaScript language itself provides: strings, arrays, Math, console. Node adds its own tools on top, for things a web page cannot do, such as reading files on your computer. The most basic is process, an object describing the program that is running right now. Try one line that uses it, in a file named show-args.ts:
console.log(process.argv);
node show-args.ts runs it happily (13.9 explains what it shows), but npx tsc objects:
show-args.ts:1:13 - error TS2591: Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig.
Node knows about process, because Node provides it, but the type checker only knows what it has types for, and it has no types for Node’s extras. The fix comes in a package. A type definitions package holds only types: no code that runs, just descriptions of what something else provides, so the checker can check your use of it. The types for Node live in a package named @types/node. (Names that start with @types/ all hold type definitions; the part before the slash is a group name on the npm registry.) Install it as a development tool, since nothing runs from it:
npm install --save-dev @types/node
Then do the second half of what the message says: tell the checker to use these types, by adding a "types" setting to tsconfig.json. Here is the full file from today on:
{
"compilerOptions": {
"strict": true,
"noEmit": true,
"target": "ES2024",
"module": "nodenext",
"types": ["node"],
"erasableSyntaxOnly": true,
"allowImportingTsExtensions": true
}
}
"types": ["node"] is a list of type-definition packages to load into every file, named without the @types/ part. Now npx tsc knows process, and also the type of every Node tool you import, such as readFileSync in 13.10.
Key idea
@types/node holds the types for Node’s own tools such as process. Install it with npm install --save-dev @types/node, and add "types": ["node"] to tsconfig.json.
Watch out
Installing the package but not adding "types". Recent versions of the type checker do not load installed type definitions on their own, so after only the npm install, npx tsc still prints the same TS2591 message. Read the message to the end: it asks for both steps. (Older versions loaded them automatically, so you may see projects without the setting.)
Pause and try
Question 12 · Short answer
Mia’s program uses process. She has installed @types/node, and package.json lists it under "devDependencies", but npx tsc still says Cannot find name 'process'. What is the most likely cause, and why would node run the program anyway?
Check your reasoning
Model answer: Her tsconfig.json does not have "types": ["node"], so the checker does not load the Node types even though they are installed; adding that setting fixes the check. node runs the program anyway because process is provided by Node itself; type definitions only tell the checker about it, and Node never reads types.
A complete answer must:
- name the missing
"types": ["node"]setting intsconfig.json, and - explain that type definitions are for the checker only, while Node provides
processitself.
Reread 13.8 Type Definitions for Node if your answer differed.
13.9 Command-Line Arguments with process.argv
Every program so far has worked on values typed into the code: to grade a different class, you had to edit the file. Programs you use every day work differently: you tell them what to work on when you start them, as in node hello.ts, where hello.ts tells Node which file to run. Your own programs can read words like that too.
The words typed after the program’s name in the terminal are called command-line arguments. Node collects them in process.argv (“argument vector,” an old name for a list), an array of strings:
| Index | Holds | For node show-args.ts Ana Lee |
|---|---|---|
| 0 | The full path of the Node program itself | (depends on your computer) |
| 1 | The full path of the file being run | (…/day13/show-args.ts) |
| 2 | The first word you typed after the file name | "Ana" |
| 3 | The second word | "Lee" |
Because the first two are always there, your own arguments start at index 2, and the usual way to get just yours is slice(2), which Day 6 taught: a copy of the array from index 2 to the end.
Worked example: Reading the arguments
const args = process.argv.slice(2);
console.log(process.argv.length);
console.log(args);
console.log(`First: ${args[0]}`);Run it with two arguments:
node show-args.ts Ana Lee4
[ 'Ana', 'Lee' ]
First: Ana- Line 3:
process.argvholds the two paths plusAnaandLee: 4 elements. - Line 1 made
argsa copy from index 2, so line 4 shows only your two words. - Line 5:
args[0]is the first word you typed.
Run it again as node show-args.ts Ana "Lee Kim" and args becomes [ 'Ana', 'Lee Kim' ]: the terminal splits the words at spaces, unless you put quotes around a group of words to keep them together as one argument. Through npm, the same run is npm start -- Ana "Lee Kim" if your start script runs show-args.ts.
Every argument is a string
process.argv has the type string[], and that is literally true: whatever you type, even 2, arrives as text.
Watch out
Doing arithmetic on arguments. This program is meant to add two numbers:
const first = process.argv[2];
const second = process.argv[3];
console.log(first + second);node add-args.ts 2 3 shows:
23first is the string "2" and second is "3", and + on two strings joins them (Day 3). npx tsc accepts it, because joining strings is allowed. Convert each argument with Number, from Day 2:
const first = Number(process.argv[2]);
const second = Number(process.argv[3]);
console.log(first + second);5If the argument is not a number, such as two, Number gives NaN, and Day 4’s Number.isNaN can check for that.
An argument may be missing
Nothing forces the person running your program to type any arguments. Then index 2 simply does not exist, and, as Day 6 showed, square brackets past the end give undefined while the checker still believes the type is string:
const word = process.argv[2];
console.log(word.toUpperCase());npx tsc accepts it. node shout-crash.ts with no word stops on line 3:
TypeError: Cannot read properties of undefined (reading 'toUpperCase')
The better tool is also from Day 6: at(2) gives the same element, but its type is string | undefined, which is honest about the missing case. Now the checker refuses to let you forget it:
const word = process.argv.at(2);
console.log(word.toUpperCase());shout-unchecked.ts:3:13 - error TS18048: 'word' is possibly 'undefined'.
Narrow it with an if, as on Day 9, and give the user a helpful message instead of a crash:
const word = process.argv.at(2);
if (word === undefined) {
console.log("Please give a word to shout.");
} else {
console.log(`${word.toUpperCase()}!`);
}With node shout.ts hello:
HELLO!
With node shout.ts and no word:
Please give a word to shout.
Inside the else block the checker knows word is a string, so toUpperCase is allowed.
Key idea
Your arguments start at process.argv[2], and every one is a string. Read them with at(2), at(3), …, check for
undefined before using them, and convert numbers with Number.
Pause and try
Question 13 · Tracing
Predict exactly what this program shows when run as node predict-args.ts Ana "Lee Kim" 3.
const args = process.argv.slice(2);
console.log(args.length);
console.log(args.join(" | "));
console.log(args[1].length);Check your reasoning
3
Ana | Lee Kim | 3
7- The quotes keep
Lee Kimtogether, soargsis[ 'Ana', 'Lee Kim', '3' ]: 3 arguments. (process.argvitself has 5 elements, but line 1 dropped the first two.) join(" | ")puts a space, a bar, and a space between the three strings.args[1]is"Lee Kim": 3 letters, a space, and 3 letters, so its length is 7. The quotes were for the terminal and are not part of the string.
Reread 13.9 Command-Line Arguments with process.argv if any line differed.
Question 14 · Multiple choice
const name = process.argv[2]; and const name = process.argv.at(2); both read the first argument. What is the difference?
- There is none; they give the same value and the same type.
[2]has the typestringand can beundefinedat run time without a warning;at(2)has the typestring | undefined, so the checker makes you handle a missing argument.at(2)counts from the end of the array, so it gives the last argument.[2]gives the path of the file being run.
Check your reasoning
B. Both give the same value when it exists, and both give undefined when it does not. Only at says so in its type, so only at lets the checker protect you.
- A is wrong: the values match, but the types do not, and the type is what decides whether the checker warns you.
- C is wrong:
atcounts from the end only for a negative index, such asat(-1). - D is wrong: the file path is at index 1. Index 2 is the first word typed after it.
Reread 13.9 Command-Line Arguments with process.argv if you chose differently.
13.10 Reading a Text File
Arguments are good for a word or two, but a class list or a poem is too long to type every time. Programs keep data like that in a text file and read it. Node’s tools for files live in a module that comes with Node, called node:fs (“file system”). You import from it just as you import from your own files, except that its path is the module’s name, "node:fs", instead of ./ and a file name (line 1 of the next example).
The node: prefix marks a built-in module, one that comes with Node, so there is nothing to install (and the "types": ["node"] setting from 13.8 gives the checker its types). readFileSync reads a whole file and gives it back as one value. Make a file named todo.txt in your project folder with these three lines, and press Enter after the last one, as most editors do for you:
Buy milk
Call Grandma
Finish homework
Worked example: A file is one long string
import { readFileSync } from "node:fs";
const text = readFileSync("todo.txt", "utf8");
console.log(text.length);
console.log(text.split("\n"));38
[ 'Buy milk', 'Call Grandma', 'Finish homework', '' ]- Line 3:
readFileSync("todo.txt", "utf8")reads the file. The first argument is the file’s name; the second,"utf8", names the encoding, the rule for turning the bytes stored on disk into characters (UTF-8 is the standard one). With it, you get astring. - Line 4: the file is 38 characters: 8 + 12 + 15 letters and spaces, plus 3 line breaks, the invisible
\ncharacter from Day 3 that marks the end of each line. - Line 5: splitting at
"\n"gives the lines, plus an empty string at the end. Three line breaks cut the text into four pieces, and the last piece, after the final line break, is empty.
That empty last piece trips up almost every program that counts lines. Day 3’s trim removes line breaks as well as spaces from both ends, so trimming before splitting gives exactly the lines you can see:
import { readFileSync } from "node:fs";
const lines = readFileSync("todo.txt", "utf8").trim().split("\n");
console.log(`${lines.length} things to do:`);
for (const [index, line] of lines.entries()) {
console.log(`${index + 1}. ${line}`);
}3 things to do:
1. Buy milk
2. Call Grandma
3. Finish homework
Line 3 chains three steps: read the text, trim the final line break, split into lines. Line 5 uses entries and destructuring from Day 6 to number them.
The name readFileSync ends in Sync, short for synchronous: the program waits on that line until the whole file has been read, then continues. Day 17 shows the other kind, where a program can do other work while it waits.
Key idea
import { readFileSync } from "node:fs"; then readFileSync(name, "utf8") gives the whole file as one string. Use trim().split("\n") to get its lines without an empty one at the end.
Watch out
Forgetting "utf8". Without the encoding, readFileSync does not give a string at all. Here hi.txt holds Hi! and a line break:
import { readFileSync } from "node:fs";
console.log(readFileSync("hi.txt"));
console.log(readFileSync("hi.txt", "utf8"));<Buffer 48 69 21 0a>
Hi!Line 3 shows a Buffer, Node’s object for raw bytes: each pair of digits is one byte, and 0a is the line break. Line 4, with "utf8", gives the text (the blank line is the file’s own line break, followed by the one console.log adds). The checker knows the difference too: calling a string method such as split on the result without "utf8" is a type error.
Watch out
A file that is not there. File names are found from the terminal’s current folder, not from the folder the .ts file is in. A typo, or running the program from a different folder, gives a runtime error:
import { readFileSync } from "node:fs";
console.log("Opening the list...");
const text = readFileSync("todos.txt", "utf8");
console.log(text);Opening the list...
Error: ENOENT: no such file or directory, open 'todos.txt'ENOENT is the system’s short code for “error: no entry,” meaning no such file. Line 3 ran, so its output appears; line 4 asked for todos.txt, but the file is todo.txt. The checker cannot catch this, because whether a file exists can only be known when the program runs. Day 16 shows how a program can handle this error instead of stopping. For now, run your programs from the project folder (VS Code’s terminal starts there), and check the name in the message against the file.
Pause and try
Question 15 · Tracing
shopping.txt holds these lines, with a blank line between bread and milk and a line break after milk:
eggs
bread
milkPredict exactly what this program shows.
import { readFileSync } from "node:fs";
const text = readFileSync("shopping.txt", "utf8");
console.log(text.split("\n").length);
console.log(text.trim().split("\n").length);
const items = text.split("\n").filter((line) => line !== "");
console.log(items.join(", "));Check your reasoning
5
4
eggs, bread, milkThe text is "eggs\nbread\n\nmilk\n", with four line breaks.
- Line 4: four line breaks cut it into five pieces:
eggs,bread, an empty string for the blank line,milk, and an empty string after the last line break. - Line 5:
trimremoves only the final line break, so there are three line breaks and four pieces. The blank line in the middle is still an empty string, becausetrimtouches only the two ends. - Lines 6–7:
filterdrops every empty piece wherever it is, leaving three items, joined with,.
Reread 13.10 Reading a Text File if any line differed.
Question 16 · Short answer
read-todo-lines.ts and todo.txt are both in the day13 folder. Lee opens a terminal in the folder above day13 and types node day13/read-todo-lines.ts. The program stops with ENOENT: no such file or directory, open 'todo.txt'. The file exists. Explain why, and give two ways to fix it.
Check your reasoning
Model answer: A file name given to readFileSync is looked up from the terminal’s current folder, not from the folder holding the program. Lee’s terminal is in the folder above day13, so Node looks for todo.txt there, where it does not exist. Fixes: change into day13 (open the project folder in VS Code and use its terminal) and run node read-todo-lines.ts; or, if the program is changed to take the file name as an argument, pass the path day13/todo.txt.
A complete answer must:
- explain that the file name is found from the terminal’s current folder, and
- give a fix that makes the name point at the real file, such as running from inside
day13.
Reread 13.10 Reading a Text File if your answer differed.
Putting it together
A teacher keeps each class in a text file, one student per line: the name, then the scores, separated by commas. A student with no scores yet has just a name. class.txt:
Ana,92,88,95
Ben,75,80,68
Chloe,58,62,49
Dev
The program is a small project: a module that knows about students, and an entry point that reads the file named on the command line. The project folder holds scores.ts, main.ts, class.txt, package.json (with "type": "module" and the check and start scripts from 13.5), tsconfig.json (with "types": ["node"]), and .gitignore.
export type Student = { name: string; scores: number[] };
/** Turns one line such as "Ana,92,88,95" into a Student. */
export function parseStudent(line: string): Student {
const [name, ...rest] = line.split(",");
return { name, scores: rest.map((part) => Number(part)) };
}
/** The mean of the scores, or 0 when there are none. */
export function average(scores: number[]): number {
if (scores.length === 0) {
return 0;
}
return scores.reduce((sum, score) => sum + score, 0) / scores.length;
}import { readFileSync } from "node:fs";
import { average, parseStudent, type Student } from "./scores.ts";
const fileName = process.argv.at(2);
if (fileName === undefined) {
console.log("Usage: npm start -- <class file>");
} else {
const lines = readFileSync(fileName, "utf8").trim().split("\n");
const students: Student[] = lines.map(parseStudent);
console.log(`${fileName}: ${students.length} students`);
for (const student of students) {
const avg = average(student.scores).toFixed(1);
console.log(`${student.name.padEnd(8)}${avg.padStart(6)}`);
}
}npm run check prints no errors, and npm start -- class.txt runs node main.ts class.txt:
class.txt: 4 students
Ana 91.7
Ben 74.3
Chloe 56.3
Dev 0.0
Follow the data through both files:
| Where | What happens | Idea |
|---|---|---|
| scores.ts 1 | export type Student shares the shape with any file that imports it |
13.3 |
| scores.ts 4–7 | parseStudent splits "Ana,92,88,95" at commas; [name, ...rest] takes the first piece and the rest as an array |
13.1 |
| scores.ts 10–15 | average returns 0 for no scores, so Dev gives 0.0 rather than NaN |
13.1 |
| main.ts 1 | readFileSync from the built-in node:fs module |
13.10 |
| main.ts 2 | Two functions and a type from scores.ts; type Student is marked so Node strips it |
13.2, 13.3 |
| main.ts 4–7 | at(2) is string | undefined; with no argument the program explains how to run it |
13.9 |
| main.ts 9 | Read, trim the final line break, split into lines | 13.10 |
| main.ts 10 | lines.map(parseStudent) turns every line into a Student |
13.1 |
| main.ts 11–15 | One aligned row per student, with Day 11’s padEnd and Day 3’s padStart |
13.1 |
Number turns each score from text into a number on line 6 of scores.ts, because a file, like the command line, only ever gives you text. Nothing in main.ts knows how a line is laid out: if the teacher switches to a different separator, only parseStudent changes. Make a second file with a different class and run npm start -- other.txt; the program does not change at all, which is the point of reading input from outside the code.
Common mistakes
| Message or symptom | Usual cause | Fix |
|---|---|---|
TS2835: Relative import paths need explicit file extensions … Did you mean './x.js'? |
from "./money" with no ending |
from "./money.ts" |
TS2459: Module '"./grades.ts"' declares 'total' locally, but it is not exported. |
Importing a name with no export |
Add export, or stop importing it |
TS2724: … has no exported member named 'countwords'. Did you mean 'countWords'? |
A spelling or capitals difference | Match the exported name exactly |
does not provide an export named 'Book' (from node, after a clean check) |
A type imported without the word type |
import { type Book, … } |
Cannot use import statement outside a module (from node) |
"type": "commonjs" in package.json |
"type": "module" |
TS2591: Cannot find name 'process'. |
No @types/node, or no "types": ["node"] in tsconfig.json |
Install it with --save-dev, and add the setting |
npm error Missing script: "chek" |
A misspelled or missing script name | npm run lists the scripts |
23 instead of 5 |
Adding arguments, which are strings | Number(process.argv[2]) |
TypeError: Cannot read properties of undefined from an argument |
No argument typed, read with [2] |
at(2) and an undefined check |
ENOENT: no such file or directory |
Wrong file name, or the terminal is in a different folder | Check the name; run from the project folder |
| An empty last line when counting lines | Splitting a file that ends with a line break | trim().split("\n") |
Vocabulary
| Term | Definition | Example |
|---|---|---|
| module | A file of code with its own private names; it shares only what it exports | money.ts |
export / named export |
A keyword that shares a declaration with other modules, by name | export function tipFor(…) |
import declaration |
A line at the top of a file that brings in names from another module | import { tipFor } from "./money.ts"; |
| module path | Where an import comes from: ./ and a file name, a package name, or a built-in module |
"./money.ts", "node:fs" |
| relative import path | A module path that starts with ./ or ../, pointing at your own file |
"./grades.ts" |
| public interface | The exported names of a module; everything else is private | average, PASS_MARK |
| entry point | The file you run, which imports the others | main.ts |
| type-only import | An import marked type, which Node strips with the other types |
import { type Book } from "./books.ts"; |
| ES modules / CommonJS | The standard module system with import and export / Node’s older one |
"type": "module" |
| script | A named command in package.json, run with npm run |
"check": "tsc" |
any |
The type that allows everything and so checks nothing | An unannotated parameter without strict |
| compiler | A tool that turns code into another form; tsc with noEmit only checks |
tsc |
| dependency / devDependency | A package the program needs while it runs / one needed only while developing | a date library / typescript |
package-lock.json |
npm’s record of the exact version of every installed package | Rebuilt from by npm install |
.gitignore |
A list of files and folders Git should not save | node_modules/ |
| type definitions | A package of types only, describing code that something else provides | @types/node |
| command-line arguments | Words typed after the program’s name in the terminal | Ana in node show-args.ts Ana |
process.argv |
Node’s array of the command line: two paths, then your arguments | process.argv.at(2) |
| built-in module | A module that comes with Node, imported with the node: prefix |
"node:fs" |
| encoding | The rule for turning stored bytes into characters | "utf8" |
| Buffer | Node’s object for raw bytes, given when no encoding is named | <Buffer 48 69 21 0a> |
Summary
- Every file is a module with private names.
exportshares a declaration;import { name } from "./file.ts";brings it in by its exact name, with./and the full.tsending. Imported modules run first, and only once. Import types with the wordtype, or Node crashes after a clean check. package.jsondescribes the project. Set"type": "module"so Node acceptsimport, and add scripts such as"check": "tsc"and"start": "node main.ts", run withnpm run checkandnpm start(extra words after--).- In
tsconfig.json,strictturns on full checking,modulefollows Node’s rules,targetnames the JavaScript features to expect, andnoEmitmeans check only."types": ["node"], with the@types/nodepackage, lets the checker know Node’s tools. npm install --save-dev namerecords a development tool in"devDependencies"; packages the program uses while it runs go in"dependencies". Never edit or sharenode_modules: list it in.gitignore, and rebuild it withnpm install.- Command-line arguments start at
process.argv[2]and are always strings: read them withat(2), check forundefined, and convert numbers withNumber.readFileSync(name, "utf8")fromnode:fsreads a whole file as one string; split it withtrim().split("\n").
Practice
Do these in your day13 folder, set up as today describes: "type": "module" in package.json, @types/node installed, and "types": ["node"] in tsconfig.json. First make sure npx tsc prints nothing: if any broken file from today is still in the folder (such as implicit-any.ts or shout-unchecked.ts, or a project file with a missing export or .ts ending), fix it or delete it. Then write each program yourself, check it, run it, and only then open the answer.
Question 17 · Short answer
Split the grade book. Move your Day 12 grade book’s Student type and calculation functions (average, letter grade, highest, lowest, class average) into a module named grades.ts, and import them into main.ts, which keeps the student data and the report printing. The output must not change.
Check your reasoning
One possible solution, starting from the Day 12 reference solution:
export type Student = { name: string; scores: number[] };
/** The mean of the scores, or 0 when there are none. */
export function average(scores: number[]): number {
if (scores.length === 0) {
return 0;
}
const total = scores.reduce((sum, score) => sum + score, 0);
return total / scores.length;
}
/** The letter grade for an average: 90 and above is A, then B, C, D by tens, and below 60 is F. */
export function letterGrade(average: number): string {
if (average >= 90) {
return "A";
} else if (average >= 80) {
return "B";
} else if (average >= 70) {
return "C";
} else if (average >= 60) {
return "D";
} else {
return "F";
}
}
/** The largest score, or 0 when there are none. */
export function highest(scores: number[]): number {
if (scores.length === 0) {
return 0;
}
return Math.max(...scores);
}
/** The smallest score, or 0 when there are none. */
export function lowest(scores: number[]): number {
if (scores.length === 0) {
return 0;
}
return Math.min(...scores);
}
/** The mean of the averages of the students who have scores, or 0 when nobody does. */
export function classAverage(students: Student[]): number {
const averages = students
.filter((student) => student.scores.length > 0)
.map((student) => average(student.scores));
return average(averages);
}import {
average,
classAverage,
highest,
letterGrade,
lowest,
type Student,
} from "./grades.ts";
const students: Student[] = [
{ name: "Ana", scores: [92, 88, 95] },
{ name: "Ben", scores: [75, 80, 68] },
{ name: "Chloe", scores: [58, 62, 49] },
{ name: "Dev", scores: [] },
{ name: "Elena", scores: [85, 90, 80] },
];
/** One aligned report row: name, average, grade, highest and lowest score. */
function reportRow(student: Student): string {
const name = student.name;
if (student.scores.length === 0) {
return `${name}${"0.0".padStart(12 - name.length)}${"–".padStart(7)}${"–".padStart(6)}${"–".padStart(6)}`;
}
const avg = average(student.scores).toFixed(1);
const grade = letterGrade(average(student.scores));
const high = String(highest(student.scores));
const low = String(lowest(student.scores));
return `${name}${avg.padStart(12 - name.length)}${grade.padStart(7)}${high.padStart(6)}${low.padStart(6)}`;
}
/** Print the whole report: a header, one row per student from the best average down, then a class summary. */
function printReport(students: Student[]): void {
if (students.length === 0) {
console.log("No students in the class yet.");
return;
}
const byAverage = students.toSorted(
(a, b) => average(b.scores) - average(a.scores),
);
console.log(
`Name${"Avg".padStart(8)}${"Grade".padStart(7)}${"High".padStart(6)}${"Low".padStart(6)}`,
);
console.log("-".repeat(31));
for (const student of byAverage) {
console.log(reportRow(student));
}
console.log("-".repeat(31));
const graded = students.filter((student) => student.scores.length > 0);
console.log(
`Students: ${students.length} (${students.length - graded.length} with no scores)`,
);
if (graded.length === 0) {
console.log("No scores recorded yet.");
return;
}
const classAvg = classAverage(students);
console.log(
`Class average: ${classAvg.toFixed(1)} (${letterGrade(classAvg)})`,
);
const top = byAverage[0];
console.log(`Top student: ${top.name} (${average(top.scores).toFixed(1)})`);
}
printReport(students);
console.log();
printReport([]);Name Avg Grade High Low
-------------------------------
Ana 91.7 A 95 88
Elena 85.0 B 90 80
Ben 74.3 C 80 68
Chloe 56.3 F 62 49
Dev 0.0 – – –
-------------------------------
Students: 5 (1 with no scores)
Class average: 76.8 (C)
Top student: Ana (91.7)
No students in the class yet.The calculation functions moved unchanged; each got export in front, and so did the Student type, because both files use it. main.ts imports five functions and, marked with type, the Student type; when an import is too long for one line, it is written one name per line, as here. reportRow and printReport stay in main.ts, because they are the printing, and the calculations never print. If you forget type in front of Student, npx tsc is still happy, but node main.ts stops with does not provide an export named 'Student'.
Reread 13.1 Modules: One File, One Job and 13.3 Exporting and Importing Types if your result differed.
Question 18 · Short answer
Scripts. Add check and start scripts to package.json that run tsc and node main.ts. Run both, and show what each prints.
Check your reasoning
The "scripts" field of package.json (with "type": "module" elsewhere in the same file):
"scripts": {
"check": "tsc",
"start": "node main.ts"
},npm run check shows npm’s two > lines and then nothing from tsc, meaning no type errors:
> day13@1.0.0 check
> tscnpm start shows the two > lines and then the grade book’s report from the previous exercise:
> day13@1.0.0 start
> node main.ts
Name Avg Grade High Low
-------------------------------
Ana 91.7 A 95 88(and the rest of the report). day13 is your project’s "name" and 1.0.0 its "version". The check script says tsc, not npx tsc, because npm finds the project’s tools for its scripts, and start can be run as npm start without run. If npm reports Missing script, check the spelling and that package.json is saved.
Reread 13.5 Scripts and npm run if your result differed.
Question 19 · Short answer
Word count. Write wc.ts, which takes a file name from process.argv and prints the file’s line, word, and character counts. Count a line for every line break, words as the pieces between spaces on each line (ignoring empty ones), and characters as the length of the whole text. Print a usage message if no file name is given. Test it on a short poem saved as poem.txt.
Check your reasoning
One possible solution:
import { readFileSync } from "node:fs";
const fileName = process.argv.at(2);
if (fileName === undefined) {
console.log("Usage: node wc.ts <file name>");
} else {
const text = readFileSync(fileName, "utf8");
const lines = text.split("\n");
let words = 0;
for (const line of lines) {
words += line.split(" ").filter((word) => word !== "").length;
}
console.log(`Lines: ${lines.length - 1}`);
console.log(`Words: ${words}`);
console.log(`Characters: ${text.length}`);
}With this poem.txt (a blank line in the middle, and a line break at the end):
The fog comes
on little cat feet.
It sits looking
over harbor and citynode wc.ts poem.txt (or npm start -- poem.txt if your start script runs wc.ts) shows:
Lines: 5
Words: 14
Characters: 72Line 3 reads the argument with at(2), so the checker insists on the undefined check on line 5. Line 8 reads the whole file as one string. Splitting it at "\n" gives one piece more than there are line breaks (the empty piece after the last one), so line 14 subtracts 1, which counts the blank line in the middle but not the empty piece at the end. For words, line 12 splits each line at spaces and keeps only the non-empty pieces, so double spaces and the blank line add nothing. The character count is text.length, which includes the line breaks. These match the counts given by the wc command that macOS and Linux come with, for a file that ends with a line break.
Reread 13.9 Command-Line Arguments with process.argv and 13.10 Reading a Text File if your result differed.
Review questions
Question 20 · Tracing
Four modules import each other like this. Predict exactly what node main.ts shows.
console.log("tax.ts runs");
export const TAX_RATE = 0.08;import { TAX_RATE } from "./tax.ts";
console.log("cart.ts runs");
export function withTax(price: number): number {
return price * (1 + TAX_RATE);
}import { TAX_RATE } from "./tax.ts";
console.log("receipt.ts runs");
export function taxLine(): string {
return `Tax rate: ${TAX_RATE * 100}%`;
}import { withTax } from "./cart.ts";
import { taxLine } from "./receipt.ts";
console.log("main.ts runs");
console.log(taxLine());
console.log(withTax(50));Check your reasoning
tax.ts runs
cart.ts runs
receipt.ts runs
main.ts runs
Tax rate: 8%
54main.tsline 1 importscart.ts. Beforecart.tsruns, its own import is handled:tax.tsruns (tax.ts runs). Thencart.tsruns (cart.ts runs).main.tsline 2 importsreceipt.ts, which also importstax.ts.tax.tshas already run, so Node hands over the sameTAX_RATEwithout running it again. Thenreceipt.tsruns.- Only now does
main.tsrun its own lines: its message, the tax line (0.08 × 100 is 8), andwithTax(50), which is 50 × 1.08 = 54.
tax.ts runs appears once, even though two modules import it.
Reread 13.2 What Importing Runs, and What Stays Private if your order differed.
Question 21 · Debugging
This program should print the larger of two numbers given on the command line. npx tsc accepts it, but node max-arg.ts 10 9 shows the wrong answer. Predict what it shows, explain why, and fix it.
const a = process.argv[2];
const b = process.argv[3];
console.log(`Larger: ${a > b ? a : b}`);Check your reasoning
Larger: 9Both arguments are strings, "10" and "9", and > on two strings compares them character by character, as on Day 4: "1" comes before "9", so "10" > "9" is false and the program picks "9". The checker allows comparing two strings, so it cannot warn you. Convert each argument with Number first:
const a = Number(process.argv[2]);
const b = Number(process.argv[3]);
console.log(`Larger: ${a > b ? a : b}`);Larger: 10Reread 13.9 Command-Line Arguments with process.argv if you missed it.
Question 22 · Debugging
npx tsc rejects main.ts. Quote the important part of the message, explain it, and give the fix.
export function countWords(text: string): number {
return text.split(" ").filter((word) => word !== "").length;
}import { countwords } from "./words.ts";
console.log(countwords("the fog comes"));Check your reasoning
main.ts:1:10 - error TS2724: '"./words.ts"' has no exported member named 'countwords'. Did you mean 'countWords'?An exported member is an exported name. Imports are matched to exports by exact spelling, and capitals count, so countwords is a different name from countWords. The checker even suggests the right one. Fix the import (and the call on line 3) to countWords:
import { countWords } from "./words.ts";
console.log(countWords("the fog comes"));3If the broken version were run without checking, Node would stop with does not provide an export named 'countwords'.
Reread 13.1 Modules: One File, One Job if you missed it.
Question 23 · Tracing
shopping.txt is the file from question 15 (eggs, bread, a blank line, milk, and a final line break). Predict exactly what node has-item.ts shopping.txt milk shows.
import { readFileSync } from "node:fs";
const fileName = process.argv.at(2);
const wanted = process.argv.at(3);
if (fileName === undefined || wanted === undefined) {
console.log("Usage: node has-item.ts <file> <item>");
} else {
const items = readFileSync(fileName, "utf8").trim().split("\n");
const found = items.includes(wanted);
console.log(`${wanted}: ${found ? "on the list" : "not on the list"}`);
console.log(`${items.length} lines read`);
}Check your reasoning
milk: on the list
4 lines read- Lines 3–4:
fileNameis"shopping.txt"andwantedis"milk", so neither isundefinedand theelseblock runs. Inside it, the checker knows both are strings. - Line 9:
trimremoves only the final line break, soitemsis[ 'eggs', 'bread', '', 'milk' ]: four lines, including the empty one from the blank line in the middle. - Line 10:
includes("milk")istrue.
Run with node has-item.ts shopping.txt and no item, and wanted is undefined, so the program prints its usage line instead.
Reread 13.10 Reading a Text File and 13.9 Command-Line Arguments with process.argv if any line differed.
Question 24 · Multiple choice
A project’s package.json contains "type": "module", "scripts": { "check": "tsc", "start": "node main.ts" }, and "devDependencies" listing typescript and @types/node. Which statement is true?
node main.tscannot run untilnpm installhas downloadedtypescript.- After
npm install,npm start -- data.txtrunsnode main.ts data.txt, andnpm run checkruns the type checker fromnode_modules. - The project should be shared with its
node_modulesfolder, ornpm startwill not work. @types/nodemust be moved to"dependencies", because the program usesprocesswhile it runs.
Check your reasoning
B. Words after -- are added to the script’s command, and npm finds the project’s tools for its scripts.
- A is wrong: running needs only Node, which strips types itself;
typescriptis a development tool used for checking. - C is wrong:
node_modulesis left out (and listed in.gitignore) becausenpm installrebuilds it frompackage.jsonandpackage-lock.json. - D is wrong:
processis provided by Node itself.@types/nodeholds only types, which nothing reads while the program runs, so it is a development tool.
Reread 13.5 Scripts and npm run and 13.7 Installing Packages if you chose differently.
Question 25 · Short answer
Mia wants to share her day13 project so that anyone can install and run it with npm. List what her package.json, tsconfig.json, and .gitignore must contain for today’s programs, and the three commands a classmate types after downloading it. Give a reason for each item.
Check your reasoning
Model answer:
package.json:"type": "module", so Node acceptsimportandexport;checkandstartscripts, so nobody has to guess the commands or the entry point;typescriptand@types/nodeunder"devDependencies", sonpm installknows to install them. Also sharepackage-lock.json, so the install gets exactly the same versions.tsconfig.json:"strict": truefor full checking,"noEmit": truesotsconly checks,"module": "nodenext"so the checker follows Node’s rules,"target": "ES2024"so it knows the modern built-ins, and"types": ["node"]so it knowsprocessandnode:fs(plus the two settings from Day 1 that match what Node can run)..gitignore:node_modules/, because that folder is large and is rebuilt bynpm install.- Commands:
npm install(rebuildnode_modules),npm run check(check the types),npm start(run it, adding-- file.txtif the program needs an argument).
A complete answer must include "type": "module", the two scripts, the devDependencies, "types": ["node"], node_modules/ in .gitignore, and npm install as the first command.
Reread 13.4 package.json and the Module Type, 13.7 Installing Packages, and 13.8 Type Definitions for Node if your list differed.
Go further
The TypeScript Handbook’s chapter on modules covers more ways to import and export, including default exports, a second style you will see in other people’s code: TypeScript Handbook: Modules. npm’s own documentation explains what a package is and how package.json describes one: npm Docs: About packages and modules.
Reflection
Check each statement. If the answer is “not yet,” reread the linked subsection.
- I can move functions into a module with export and import them with the right path. Reread
- I can keep a helper private and explain in what order imported modules run. Reread
- I can export a type and import it with the word type so Node does not crash. Reread
- I can set "type": "module" in package.json and explain what goes wrong without it. Reread
- I can add check and start scripts and run them with npm, passing extra words after --. Reread
- I can explain what strict, module, target, and noEmit do in tsconfig.json. Reread
- I can tell dependencies from devDependencies and explain why node_modules goes in .gitignore. Reread
- I can install @types/node and add "types": ["node"] so the checker knows process. Reread
- I can read command-line arguments safely with process.argv.at and convert numbers. Reread
- I can read a text file with readFileSync and split it into lines without an empty one. Reread