Sub topic 5
Compiling your first file with tsc
This chapter walks through the first full compile: a source file goes in, tsc checks it, and JavaScript comes out. It also covers what happens when the check fails, which surprises many newcomers.
Prerequisites
This chapter assumes you have:
- Node.js and npm installed, and you can run commands in a terminal.
- A project folder with a
package.json. - TypeScript installed as a dev dependency, as shown in the previous chapter.
- Working knowledge of JavaScript functions, objects, and modules.
If npx tsc --version prints a version number inside your project folder, you are ready.
What tsc does in one run
The tsc command (the TypeScript compiler) does two jobs in a single run:
- It reads your
.tsfiles, builds a model of every type, and reports errors. - It writes
.jsfiles with the type syntax removed.
These jobs are separate. Emit does not depend on the check passing, unless you ask it to. The diagram shows the default flow.
Create the source file
Make a src folder and add src/index.ts. The function below has a typed parameter and a typed return value.
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Ada"));
console.log(greet(42));The last line is a deliberate mistake. 42 is a number, but greet declares that name is a string. Plain JavaScript would run this without complaint.
Compile it
Run the compiler on the file and send the output to a dist folder:
npx tsc src/index.ts --outDir dist
node dist/index.jsnpx runs the tsc binary from your project's node_modules/.bin. That is the version you pinned, not one installed globally.
The first command prints an error similar to this:
src/index.ts(6,19): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.The exact layout depends on your TypeScript version and whether the terminal supports color. Every error has the same parts:
| Part | Example | Meaning |
|---|---|---|
| File | `src/index.ts` | The file that contains the problem |
| Position | `(6,19)` or `6:19` | Line 6, column 19 |
| Code | `TS2345` | A stable error number you can search for |
| Message | `Argument of type 'number'...` | What the checker found |
The surprise: output is written anyway
After the error, node dist/index.js still runs and prints:
Hello, Ada!
Hello, 42!By default, tsc writes JavaScript even when it finds type errors. The type check is advice that the compiler gives you. It does not stop the output. This default exists so that you can migrate a large JavaScript codebase gradually without a blocked build.
You can tell the two outcomes apart by the exit code:
- Exit code
0: no errors. - Exit code
2: errors were reported, but files were still written. - Exit code
1: errors were reported and nothing was written. This happens withnoEmitOnError, covered in a later chapter.
You can see the code in a POSIX shell:
npx tsc src/index.ts --outDir dist
echo "tsc exit code: $?"A CI step that runs tsc fails on any non-zero exit code. A plain npx tsc && node dist/index.js also stops at the error, because && only continues after exit code 0. The files exist on disk, but the shell never runs them.
Fix the error and recompile
Remove the bad call so the file ends like this:
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Ada"));
console.log(greet("Grace"));Compile and run again:
npx tsc src/index.ts --outDir dist
node dist/index.jstsc prints nothing and exits with 0. Silence means success. Node prints:
Hello, Ada!
Hello, Grace!Look at the emitted JavaScript
Open dist/index.js. The type annotations are gone:
function greet(name) {
return "Hello, ".concat(name, "!");
}
console.log(greet("Ada"));
console.log(greet("Grace"));Two things changed, and they have different causes.
- The
: stringannotations were erased. This is type erasure. It always happens, because the types exist only for the checker. - The template literal became a
concatcall. This is a downlevel transform, which depends on thetargetoption. When no target is set,tscfalls back to a default that varies by TypeScript version, and older defaults target a much older JavaScript edition than your Node.js supports.
The exact helper code you see (concat, +, or an untouched template literal) depends on the compiler version and target. What matters is knowing that types are erased and syntax may also be rewritten. Setting target explicitly, as the next section shows, removes the guesswork.
Why command-line files are a dead end
The command above passes the file name directly. This works for a first experiment, but it has a limit. When you list files on the command line, tsc ignores tsconfig.json. Recent versions may report an error if a config file exists and you also pass files. If you want strict or a particular target, you would need to repeat every flag on every run.
That is why real projects use a config file. Generate a starter file:
npx tsc --initThen replace its contents with a minimal configuration:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"rootDir": "src",
"outDir": "dist",
"sourceMap": true,
"skipLibCheck": true
},
"include": ["src"]
}Run tsc with no file arguments, and it finds tsconfig.json in the current folder and compiles everything under include:
npx tsc
node dist/index.jsThe next chapter covers each option. For now, notice that target: "ES2022" leaves template literals alone, so dist/index.js now contains the template literal exactly as you wrote it.
Useful flags for a first run
These flags help you see what tsc is doing without editing any config:
| Flag | Effect |
|---|---|
| `--version` | Prints the compiler version in use |
| `--showConfig` | Prints the final configuration after defaults and inheritance |
| `--listEmittedFiles` | Lists every file written during the run |
| `--listFiles` | Lists every file the compiler read, including library files |
| `--noEmit` | Checks types and writes nothing |
Try --listEmittedFiles after a successful build:
npx tsc --listEmittedFilesYou should see paths such as dist/index.js and dist/index.js.map. The .map file exists because the config sets sourceMap: true.
Common errors on a first compile
tsc: command not found: You rantscdirectly instead ofnpx tsc, and no global install exists. Usenpx tscor add a script topackage.json.error TS18003: No inputs were found in config file: Theincludepath matches no.tsfiles. Check thatsrc/index.tsexists and that the folder name matches.Cannot find name 'console': Node's type declarations are missing. Install them withnpm install --save-dev @types/node. Declaration files are covered in a later chapter.Cannot find module './dist/index.js'when running Node: The compile did not write output, or theoutDirdiffers from the path you ran. Use--listEmittedFilesto check.- Stale files in
dist:tscnever deletes old output. If you renameindex.ts, the oldindex.jsstays behind. Deletedistbefore a full rebuild.
Add a script
Typing npx tsc is fine while experimenting. For a project, record the commands in package.json so everyone runs the same thing:
{
"scripts": {
"build": "tsc",
"typecheck": "tsc --noEmit",
"start": "node dist/index.js"
}
}npm scripts put node_modules/.bin on the path, so tsc there resolves to the project's pinned version. Run them with npm run build and npm run typecheck.
Exercise
You run npx tsc src/index.ts --outDir dist on a file with one type error. The terminal shows the error, yet dist/index.js exists. Why, and what exit code does tsc return?
Show answer
By default, tsc reports type errors but still emits JavaScript, because type checking and emit are separate steps and noEmitOnError is off. The exit code is 2, which means errors were reported but output was generated.
Exercise
A teammate runs npx tsc src/index.ts in a project that has "strict": true in tsconfig.json, and sees no strictness errors. What is the likely cause, and what is the fix?
Show answer
Passing files on the command line makes tsc ignore tsconfig.json, so strict mode was never applied. Run npx tsc with no file arguments so it reads the config file, or repeat the options as flags.
Exercise
After compiling, dist/index.js no longer contains : string, but a template literal also changed into a concat call. Which change is type erasure, and which depends on the target option?
Show answer
Removing : string is type erasure, which always happens. Rewriting the template literal is a downlevel transform, and it happens only when the target is an older JavaScript edition that lacks template literals in the form you wrote. Setting a newer target such as ES2022 leaves the template literal alone.