Sub topic 2
Compiling Your First File with `tsc`
Assume you know basic JavaScript functions, objects, and modules. You also need Node.js, npm, and basic terminal commands.
Compiling a file
TypeScript adds static types to JavaScript. The TypeScript compiler, called tsc, checks those types and produces JavaScript that runtimes such as Node.js can execute.
Create a project and install TypeScript locally:
mkdir ts-demo && cd ts-demo
npm init -y
npm install --save-dev typescript
npx tsc --versionA local installation keeps the compiler version in package.json. npx runs that project version.
Create src/index.ts:
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Ada"));
console.log(greet(42));Compile it directly:
npx tsc src/index.ts --outDir distThe compiler reports an error because 42 is not a string. Remove that line, then run the compiler again:
node dist/index.jsType annotations help tsc find mistakes before execution. They are erased from the emitted JavaScript.
Configuring the project with `tsconfig.json`
Passing a file on the command line is useful for a quick test, but it makes tsc ignore your project configuration. A tsconfig.json file records the project’s source files and compiler behavior.
Create one with:
npx tsc --initReplace its contents with this focused configuration:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"rootDir": "src",
"outDir": "dist",
"sourceMap": true,
"skipLibCheck": true
},
"include": ["src"]
}Now compile the whole project:
npx tscThe compiler options you need first
| Option | Purpose |
|---|---|
| `target` | Selects the JavaScript version to emit |
| `module` | Controls how imports and exports are compiled |
| `rootDir` | Identifies the source directory |
| `outDir` | Identifies the output directory |
| `strict` | Enables strong type checking |
| `include` | Selects files included in the project |
strict includes checks such as strictNullChecks. These checks often expose missing cases early.
Exercise
Which command compiles a project using its tsconfig.json without writing JavaScript files?
Show answer
npx tsc --noEmit