TypeScript tsconfig
A tsconfig.json file tells the TypeScript compiler how to work on a project. The compiler reads the file before it checks any code in that project.
A tsconfig.json file
The settings sit inside compilerOptions. This config targets ES2020 and turns strict checks on.
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"outDir": "out",
"strict": true
},
"include": ["main.ts"]
}A strict null check refuses unsafe code
strict includes a check for values that may be null. This code reads length without a check, so the compiler refuses it.
let label: string | null = null;
console.log(label.length);The same shape with a null check
A null check splits the code into two safe branches. The null branch logs a fallback line.
function showLength(label: string | null): void {
if (label === null) {
console.log("no label");
} else {
console.log(label.length);
}
}
showLength(null);Example
function greet(name: string): string {
return "Hello, " + name;
}
const message: string = greet("Ada");
console.log(message);Key points
- target sets the JavaScript version the compiler emits
- outDir sets the folder that receives the emitted JavaScript
- strict turns on the strongest set of type checks
- include lists the files the project compiles
- The compiler reads tsconfig.json from the project folder
In this example, the project config from this lesson compiles the program. greet takes a string and returns a string. The call passes a name and the result is stored in a string variable. The logged line is the greeting the compiled program prints.
Note
tsconfig.json holds settings only. It contains no program code
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
What does the strict setting in tsconfig.json do?