Sub topic 1
Running the TypeScript compiler and finding your errors
Prerequisites
You should know basic JavaScript, including functions, objects, arrays, and modules. You should also understand TypeScript annotations, interfaces, and union types. This chapter assumes that Node.js, npm, and a terminal are available.
Set up a compiler check
The TypeScript compiler is called tsc. It reads TypeScript files, checks them against your configuration, and reports diagnostics. A diagnostic is a structured compiler message about a problem.
Install TypeScript in a project with:
npm install --save-dev typescriptCreate a tsconfig.json file:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"noEmit": true
},
"include": ["src"]
}The include setting tells the compiler to check files under src. The noEmit setting prevents JavaScript output. This is useful when you want to check types without building the project.
Create src/index.ts:
function double(n: number): number {
return n * 2;
}
const input: string = "21";
double(input);Run the compiler through the project-local executable:
npx tsc --noEmit --pretty falseYou should see a diagnostic similar to this:
src/index.ts(8,8): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.Locate the problem
Read the diagnostic from left to right:
| Part | Meaning |
|---|---|
| `src/index.ts` | The file containing the problem |
| `(8,8)` | Line 8, column 8 |
| `error` | The diagnostic severity |
| `TS2345` | The diagnostic code |
| Remaining text | The compiler's explanation |
Open line 8 first. The call passes input, whose type is string, to double, which requires a number. The compiler has identified a type boundary where the value does not meet the function's contract.
The first useful action is usually to inspect the reported location and the declarations involved. Do not begin by changing compiler settings or adding an assertion. First determine what type the value has and what type the operation requires.
A compiler run can report several diagnostics. Fixing one problem may remove others, because later checks depend on earlier values. Run the compiler again after each focused fix so that you work from the current error list.
Check only the project you intend
When a repository has multiple configurations, pass the intended file explicitly:
npx tsc --project tsconfig.json --noEmit --pretty falseThis avoids accidentally checking a different directory or using a default configuration. In an editor, compare its reported file list with the files checked by your terminal command.
Exercise
Which part of src/index.ts(8,8): error TS2345: ... tells you where to begin investigating?
Show answer
Begin at line 8, column 8 in src/index.ts, then inspect the actual and required types involved in that expression.