Setting up TypeScript: tsc and tsconfig.json
Course contents (16 lessons)
- Getting started
- Why TypeScript? What it is and what it is not
- Setting up TypeScript: tsc and tsconfig.json
- Core types
- Basic types: primitives, arrays, tuples, any and unknown
- Typing functions: parameters, returns, optionals and overloads
- Objects, interfaces and type aliases
- Unions, literals and enums
- Union types and type narrowing
- Literal types, enums and as const
- Classes and generics
- Classes in TypeScript
- Generics: writing reusable typed code
- Built-in utility types: Partial, Pick, Omit, Record and more
- Advanced types
- Mapped and conditional types
- Modules, type imports and declaration files
- TypeScript in real projects
- Typing async code and API responses
- Strict mode and compiler flags that matter
- Migrating a JavaScript project to TypeScript
- Final project: a type-safe task manager
What you need
You need Node.js (a current LTS version) and a code editor. VS Code is the natural choice, since it ships with TypeScript support built in. Check Node with node --version.
Installing TypeScript in a project
Install TypeScript as a development dependency of your project, and not globally. That way everyone who works on the project uses the same version.
mkdir ts-demo
cd ts-demo
npm init -y
npm install --save-dev typescript
npx tsc --version
The last command prints a version such as Version 5.6.3. The examples in this course work with TypeScript 5.x. The npx prefix runs the tsc that is installed in your project.
Your first compile
Create hello.ts:
function greet(name: string): string {
return `Hello, ${name}!`;
}
const message: string = greet("TypeScript");
console.log(message);
Compile it:
npx tsc hello.ts
TypeScript creates hello.js next to the file. Look at it. The type annotations are gone, and the rest is almost identical, as the compiler may rewrite newer syntax to suit the target. Run it with node hello.js.
To check for errors without writing any files, use npx tsc --noEmit. This is what I use in continuous integration.
Running TypeScript directly
For quick experiments you do not always need to compile. Recent versions of Node.js can run a .ts file directly with node hello.ts. They simply strip the types, with no type checking, and they only support syntax that is plain JavaScript once the types are removed. Other tools, such as tsx, offer similar convenience. Remember that none of these check your types. Keep running tsc --noEmit for that.
tsconfig.json
Typing file names into tsc does not scale. A tsconfig.json file in the project root tells the compiler how to behave and which files to include. Create one with:
npx tsc --init
The generated file has many commented options. This is a clean version that I would use for a new project:
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2022", "DOM"],
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"rootDir": "src",
"outDir": "dist",
"sourceMap": true
},
"include": ["src"]
}
Now npx tsc compiles every file in src into dist.
The options that matter
| Option | What it does |
|---|---|
target | Which JavaScript version the output uses. ES2022 is fine for current browsers and Node |
module | The module format of the output. ESNext keeps import/export. Use NodeNext for Node projects that run the output directly |
moduleResolution | How imports are found. Bundler suits projects that use Vite, webpack or esbuild. NodeNext suits plain Node |
lib | Which built-in types are available. Include DOM for browser code |
strict | Turns on the family of strict checks. Always turn it on for a new project |
noUncheckedIndexedAccess | Makes array[0] possibly undefined, which is the honest type |
rootDir / outDir | Where your sources are and where output goes |
sourceMap | Lets debuggers show your .ts files |
skipLibCheck | Skips type checking inside .d.ts files from packages, which saves time and avoids errors that are not yours |
noEmit | Only check, do not write files. Used when a bundler does the build |
Who does the build
There are two common setups, and it helps to know which one you have.
- tsc builds everything. Good for libraries and Node services.
tscproduces the final JavaScript. - A bundler builds, tsc only checks. Common for web apps made with Vite, Next.js or similar. These tools strip types very quickly but do not check them, so you run
tsc --noEmitas a separate step. In this setup you set"noEmit": trueand may also want"isolatedModules": true, and a newer option"verbatimModuleSyntax": truemakes import handling explicit.
Useful scripts
In package.json:
"scripts": {
"build": "tsc",
"typecheck": "tsc --noEmit",
"watch": "tsc --watch"
}
npm run watch recompiles whenever you save, and prints errors as you work.
A quick test of your setup
Create src/index.ts:
const numbers: number[] = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);
console.log(doubled);
// This line would fail the build:
// const wrong: string = doubled[0];
Run npx tsc, then node dist/index.js. You should see [ 2, 4, 6, 8 ]. Then uncomment the last line and run tsc again to watch the error. Note that, by default, tsc still writes output even when there are errors. Add "noEmitOnError": true if you want the build to stop instead.
Editor tips
VS Code underlines errors, shows types when you hover, and has a rename command on F2 that updates every use. Press Ctrl+Shift+P and run "TypeScript: Select TypeScript Version" if you want the editor to use the version installed in your project, rather than the one that ships with VS Code. Mismatched versions cause confusing differences between the editor and the build.
Common mistakes
- Installing TypeScript only globally. Team members and servers end up with different versions.
- **Leaving
strictoff.** You lose most of the benefit. Start strict. - **Wrong
includeorrootDir.** Files are silently not compiled. Check what tsc sees withnpx tsc --listFiles. - **Using
module: CommonJSby accident in a project that usesimport.** The output will not run in the setup you expect. - Assuming the bundler checks types. Most do not. Add a typecheck script.
- Expecting JS output to stop on errors. Use
noEmitOnErrorif you want that.
Try it yourself
- Create a new folder, install TypeScript, and run
npx tsc --init. Open the file and read the comments of three options you do not know. - Create
src/index.tsand compile it todistusing the config above. - Add
"noEmitOnError": true, introduce a type error, and confirm that no output is written. - Add the three scripts to
package.jsonand run each one.
function greet(name: string): string {
return `Hello, ${name}!`;
}
const message: string = greet("TypeScript");
console.log(message);
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account