Getting Started with TypeScript
TypeScript files use the .ts extension (or .tsx for files containing JSX). The TypeScript compiler, tsc, reads these files, checks them for type errors, and outputs plain JavaScript. Let’s get set up.
Installing TypeScript
Since you already have Node.js installed, you can install the TypeScript compiler globally:
npm install -g typescript
Verify the installation:
tsc -v
# Version 5.x.x
Your First TypeScript File
Create a file named hello.ts:
const greeting: string = "Hello, TypeScript!";
console.log(greeting);
Compile it:
tsc hello.ts
This produces a hello.js file in the same directory. By default, TypeScript targets ES5, so you will typically see:
var greeting = "Hello, TypeScript!";
console.log(greeting);
Notice that the : string type annotation is gone. TypeScript erases all type information during compilation. The output is plain JavaScript that any runtime can execute.
Now run the generated file:
node hello.js
# Hello, TypeScript!
Type Checking
TypeScript is most useful when you make a mistake. Modify hello.ts:
const greeting: string = "Hello, TypeScript!";
console.log(greeting.toUppercase()); // typo!
Compile again:
tsc hello.ts
# error TS2551: Property 'toUppercase' does not exist on type 'string'.
# Did you mean 'toUpperCase'?
TypeScript caught the typo before the code ran. That is the main benefit of TypeScript: you get errors at compile time instead of at runtime.
Configuring the Compiler with tsconfig.json
For real projects, you do not want to pass file names to tsc manually. Instead, create a tsconfig.json file at the root of your project:
{
"compilerOptions": {
"target": "ES2020",
"module": "ES2020",
"strict": true,
"outDir": "./dist",
"esModuleInterop": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}
Key options:
| Option | What It Does |
|---|---|
target |
The JavaScript version to compile to (e.g., ES2020) |
module |
The module system to use (e.g., ES2020, CommonJS) |
strict |
Enables all strict type-checking options |
outDir |
Where compiled .js files go |
esModuleInterop |
Allows default imports from CommonJS modules |
include |
Which files to compile |
With a tsconfig.json in place, you can run tsc with no arguments. It will find and compile all matching files.
Running TypeScript Directly
Compiling to JavaScript and then running the output gets tedious during development. Tools like tsx let you run TypeScript files directly:
npm install -g tsx
tsx hello.ts
# Hello, TypeScript!
Internally, tsx transpiles your code as it runs, so you do not have to manage a manual build step. It is convenient for development, but it does not replace full type-checking (tsc --noEmit) or a proper production build.