Tutorials / TypeScript: Beginner to Advanced / Setting up TypeScript: tsc and tsconfig.json

Setting up TypeScript: tsc and tsconfig.json

14 min read typescript
Course contents (16 lessons)
  1. Getting started
  2. Why TypeScript? What it is and what it is not
  3. Setting up TypeScript: tsc and tsconfig.json
  4. Core types
  5. Basic types: primitives, arrays, tuples, any and unknown
  6. Typing functions: parameters, returns, optionals and overloads
  7. Objects, interfaces and type aliases
  8. Unions, literals and enums
  9. Union types and type narrowing
  10. Literal types, enums and as const
  11. Classes and generics
  12. Classes in TypeScript
  13. Generics: writing reusable typed code
  14. Built-in utility types: Partial, Pick, Omit, Record and more
  15. Advanced types
  16. Mapped and conditional types
  17. Modules, type imports and declaration files
  18. TypeScript in real projects
  19. Typing async code and API responses
  20. Strict mode and compiler flags that matter
  21. Migrating a JavaScript project to TypeScript
  22. 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

OptionWhat it does
targetWhich JavaScript version the output uses. ES2022 is fine for current browsers and Node
moduleThe module format of the output. ESNext keeps import/export. Use NodeNext for Node projects that run the output directly
moduleResolutionHow imports are found. Bundler suits projects that use Vite, webpack or esbuild. NodeNext suits plain Node
libWhich built-in types are available. Include DOM for browser code
strictTurns on the family of strict checks. Always turn it on for a new project
noUncheckedIndexedAccessMakes array[0] possibly undefined, which is the honest type
rootDir / outDirWhere your sources are and where output goes
sourceMapLets debuggers show your .ts files
skipLibCheckSkips type checking inside .d.ts files from packages, which saves time and avoids errors that are not yours
noEmitOnly 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.

  1. tsc builds everything. Good for libraries and Node services. tsc produces the final JavaScript.
  2. 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 --noEmit as a separate step. In this setup you set "noEmit": true and may also want "isolatedModules": true, and a newer option "verbatimModuleSyntax": true makes 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 strict off.** You lose most of the benefit. Start strict.
  • **Wrong include or rootDir.** Files are silently not compiled. Check what tsc sees with npx tsc --listFiles.
  • **Using module: CommonJS by accident in a project that uses import.** 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 noEmitOnError if you want that.

Try it yourself

  1. 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.
  2. Create src/index.ts and compile it to dist using the config above.
  3. Add "noEmitOnError": true, introduce a type error, and confirm that no output is written.
  4. Add the three scripts to package.json and run each one.
typescript
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