01 setup
TypeScript is a type checker that outputs JavaScript It does not run in the browser If you think types survive runtime, you are in for a bad night
Table of Contents
Install
npm install typescript --save-dev
npx tsc --version
The current stable compiler is 7.0.x The command prints the installed version The install page prefers a project local dependency over a global one
First file
function greet(name: string): string {
return `Hello, ${name}`;
}
console.log(greet("0x1RIS"));
Type check without writing output:
tsc --noEmit hello.ts
Emit JavaScript:
tsc hello.ts
The annotations disappear in hello.js
That is the whole point , types are a development tool
tsc flags
These were checked with tsc --help:
--noEmit- check types , write nothing--strict- turn on the full strict family--target ES2022- output language level--module esnext- module syntax in output--moduleResolution bundler- resolution for modern bundlers--lib ES2022,DOM- available global types
The series verifier ran:
tsc --noEmit --strict --target ES2022 --module esnext --moduleResolution bundler --lib ES2022,DOM verify.ts
No output means pass TypeScript is quiet when it agrees with you
Strict mode
strict: true enables the important checks
The two you will feel first:
noImplicitAny- no silentanywhere a type was not writtenstrictNullChecks-nullandundefinedare not assignable to everything
New code should start strict Migrating old JavaScript can start loose and tighten later
Common errors
Cannot find name 'console'-> DOM lib is missing , add--lib DOMDuplicate identifier-> two declarations share a name , rename oneFile is not a module-> noexportin the file , add one
Read the error code TS2300 and TS2304 tell you different things
Posted