Installing TypeScript and tsc
You clone a teammate's project, type tsc, and get a different error list from theirs. The reason is usually that you are running a different compiler version. Installing TypeScript the right way — inside the project — makes every machine agree.
The rule
Install TypeScript per project; tsc turns .ts into .js.
TypeScript is an npm package, and its compiler is a command-line program called tsc (TypeScript compiler). Add it to a project as a development dependency, because it is needed to build the code, not to run it:
npm init -y
npm install --save-dev typescriptNow the compiler lives in node_modules, and its exact version is written into package.json. Run it through npx, which finds the project's local copy:
npx tsc --version # which compiler this project uses
npx tsc --init # create a starter tsconfig.json
npx tsc # compile the project using tsconfig.jsonSuppose src/tasks.ts contains:
const title: string = "Buy milk";
console.log(title.toUpperCase());Running npx tsc checks it and writes a matching .js file (where it goes depends on the settings in tsconfig.json, which gets its own lesson). If there is a type error, tsc prints it with the file name and line number — and by default it still writes the JavaScript, because the output is plain JavaScript either way.
You can also compile one file directly with npx tsc src/tasks.ts. Be aware that naming files on the command line makes tsc ignore tsconfig.json and use default settings, which surprises many people.
A global install (npm install -g typescript) works for quick experiments, but the project copy is the one that counts.
The shortcut
Think "install, init, compile" — three commands, always in that order for a new project:
Install
npm install --save-dev typescriptadds the compiler and records its version inpackage.json.
If two machines disagree about errors, check npx tsc --version on both first. A bare tsc may be running a global copy of a different version.
Drills
Answer fast — trust the rule.
Why is TypeScript usually installed with --save-dev?
Which command creates a starter tsconfig.json?
What does npx tsc do when it finds type errors, with default settings?
You run npx tsc src/tasks.ts and your strict settings seem to be ignored. Why?
Remember
- Install TypeScript per project as a dev dependency; tsc turns .ts into .js.
- Install, init, compile:
npm install --save-dev typescript,npx tsc --init,npx tsc. - Trap:
tsc file.tsskips tsconfig.json, and a baretscmay be a different global version.
