When working with TypeScript, the TypeScript compiler (tsc) is responsible for converting TypeScript code into JavaScript. Understanding how the compiler works and how to configure it is essential for building TypeScript applications effectively.
Initializing a TypeScript Project
To create a TypeScript configuration file, run:
tsc --init
This generates a file called:
tsconfig.json
The tsconfig.json file contains settings that control how TypeScript compiles your code.
Understanding compilerOptions
Inside tsconfig.json, you'll find a section called compilerOptions.
{
"compilerOptions": {
// compiler settings
}
}
This section allows you to customize how TypeScript behaves during compilation.
Compiling TypeScript Files
To compile a single file:
tsc app.ts
TypeScript generates a corresponding JavaScript file:
app.ts -> app.js
Watch Mode
Instead of manually recompiling after every change, you can use watch mode.
tsc --watch app.ts
or the shorter form:
tsc -w app.ts
The compiler continues running and automatically recompiles whenever the file changes.
Loading diagram…
JavaScript Is Generated Even When Errors Exist
By default, TypeScript still emits JavaScript files even if compilation errors occur.
let age: number = "hello";
To prevent this behavior, enable:
{
"compilerOptions": {
"noEmitOnError": true
}
}
Compiling an Entire Project
When a tsconfig.json file exists, you can simply run:
tsc
TypeScript automatically compiles all configured files in the project.
Controlling Which Files Are Compiled
files
{
"files": [
"src/index.ts",
"src/user.ts"
]
}
include
{
"include": [
"src/**/*.ts"
]
}
exclude
{
"exclude": [
"node_modules",
"dist"
]
}
Output Directory
{
"compilerOptions": {
"outDir": "./dist"
}
}
The name dist stands for distribution.
Target JavaScript Version
{
"compilerOptions": {
"target": "ES2020"
}
}
Target
Description
ES5
Older browser compatibility
ES2015 (ES6)
Modern JavaScript features
ES2020
Widely used modern target
ESNext
Latest supported JavaScript syntax
The any Type
function greet(name) {
return `Hello ${name}`;
}
Here, name is implicitly assigned the type any.
noImplicitAny
{
"compilerOptions": {
"noImplicitAny": true
}
}
Now TypeScript reports an error when a parameter implicitly becomes any.
function greet(name: string) {
return `Hello ${name}`;
}
The TypeScript compiler converts TypeScript into JavaScript and is controlled through the tsconfig.json file. Understanding options such as target, outDir, include, exclude, noEmitOnError, and noImplicitAny will help you build TypeScript projects with better structure, safer code, and a smoother development experience.