TypeScript Get Started
To get started with TypeScript you need Node.js (version 20 or newer) and the TypeScript compiler, tsc. This chapter installs it, compiles a file and sets up a tsconfig.json.
Installing TypeScript
Install TypeScript as a development dependency of your project so every developer uses the same version. Then run it with npx.
npm init -y
npm install --save-dev typescript
npx tsc --versionVersion 5.6.3
Compiling Your First File
Write a .ts file and compile it. tsc checks types and writes a .js file next to it, which you run with Node.
// hello.ts
const items: string[] = ["tea", "rice"];
console.log(`You have ${items.length} items`);
// terminal:
// npx tsc hello.ts
// node hello.jsYou have 2 items
Creating tsconfig.json
A tsconfig.json file tells tsc which files to compile and how. Create one with npx tsc --init, then simplify it. With a config, you just run npx tsc.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src"]
}Important Compiler Options
- strict: turns on all strict checks, including strictNullChecks. Always enable it in new projects
- target: which JavaScript version to output
- module: the module system for the output (ESNext, NodeNext, CommonJS)
- outDir / rootDir: where compiled files go and where sources live
- noEmit: only type-check, useful when a bundler like Vite does the compiling
Faster Ways to Run TypeScript
During development, tools run .ts files directly. tsx runs files instantly (npx tsx app.ts). Recent Node.js versions can also strip types natively, and Deno and Bun run TypeScript out of the box. Vite projects created with the react-ts or vanilla-ts templates are preconfigured. Run npx tsc --noEmit to type-check the whole project.
npx tsx src/index.ts # run directly
npx tsc --noEmit # type-check only
npx tsc --watch # recompile on saveFrequently asked questions
Should I install TypeScript globally or locally?
Locally, as a devDependency. This pins the version per project and avoids differences between machines. Use npx tsc to run it.
What does strict mode do in TypeScript?
It enables a group of checks such as strictNullChecks and noImplicitAny. It catches far more bugs and is recommended for all new code.
Does TypeScript still output JavaScript if there are type errors?
By default, yes. tsc reports errors but still emits files. Set noEmitOnError to true to stop output when errors exist.