TypeScript Get Started
Getting started with TypeScript means installing the compiler, creating a config file, and learning the compile-then-run workflow.
Installing TypeScript
TypeScript is distributed as an npm package. Assuming you already have Node.js and npm installed, you can add TypeScript to a project as a development dependency, or install it globally so the tsc command is available anywhere on your machine.
Example
# Install locally in a project (recommended)
npm install --save-dev typescript
# Or install globally
npm install -g typescript
# Check the installed version
npx tsc --versionCompiling your first file
Create a file named hello.ts with a small piece of typed code, then run the TypeScript compiler against it. The compiler produces a hello.js file containing plain JavaScript, which you can then run with Node.
Example
// hello.ts
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("World"));Example
# Compile hello.ts into hello.js
npx tsc hello.ts
# Run the compiled JavaScript
node hello.js
// Output: Hello, World!The tsconfig.json file
Real projects almost always use a tsconfig.json file to configure how the compiler behaves - which JavaScript version to target, how strict the type checking should be, where to put compiled files, and which files to include. Running `tsc --init` generates a starter file with helpful comments.
- target: which version of JavaScript to compile down to (e.g. es2016, esnext).
- strict: turns on the full set of strict type-checking options - highly recommended.
- outDir: the folder where compiled .js files are written.
- rootDir: the folder containing your source .ts files.
- include / exclude: which files or folders the compiler should process.
Example
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"strict": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"]
}Exercise: TypeScript Get Started
How do you typically install the TypeScript compiler for a project?