Warm-up · Activity 1 of 7
// B1.4 · ~30 min · Beginner
Reading compiler errors: from the diagnostic to the fix
After this lesson you can read any tsc diagnostic, judge its "Did you mean" suggestion, and work through several errors from the first, finding the line that causes them.
You will be able to
- Read a diagnostic: position, TS code, message, its indented second line, and the terminal form
- Fix name, property and argument errors, and judge a "Did you mean" suggestion
- Fix several errors from the first one, find a cause on a line with no error, and run tsc again
Predict · Activity 2 of 7
Predict before you read on: which lines does tsc report for this main.ts?
let total = "0"; total++; const doubled: number = total * 2; console.log(total.toFixed(2), doubled);Practice · Activity 3 of 7
The loop said sum += prise, and tsc printed main.ts(4,10): error TS2552: Cannot find name 'prise'. Did you mean 'price'? Fill in the name, so that tsc accepts it and it prints 7.
const prices = [3, 4]; let sum = 0; for (const price of prices) { sum += ____; } console.log(sum);sum += ;Practice · Activity 4 of 7
The same program. You may change one line. Which change makes tsc report no errors at all?
let total = "0"; total++; const doubled: number = total * 2; console.log(total.toFixed(2), doubled);Practice · Activity 5 of 7
tsc prints main.ts(7,19): error TS2345: Argument of type 'string[]' is not assignable to parameter of type 'number[]'. and an indented line under it. What does the indented line say?
function total(prices: number[]): number { let sum = 0; for (const p of prices) sum += p; return sum; } const cart = ["3.5", "4.25"]; console.log(total(cart));Brain teaser · Activity 6 of 7
Brain teaser. For this file, tsc reports one error: main.ts(2,30): error TS1005: ')' expected. You add the missing ) and run npx tsc again. How many errors does it report now?
const count: number = "3"; console.log("count is", count; const label: string = 5;Apply · Activity 7 of 7
Mini-task. Put this program in main.ts and run npx tsc (or check it in the editor). It should print Fence: 13 m. Fix the first diagnostic only, run tsc again, and repeat until tsc prints nothing. Write down how many errors each run reported. Then run node main.ts.
function perimeter(width: number, height: number): number { return 2 * (width + height); } let label = "Fence"; const sides = [4, 2.5]; const metres: number = "m"; console.log(lable + ":", perimeter(sides[0]), metres);Check your work against this list
Build it yourself
Read the worked example, then write the exercises. Your code runs in your browser or on your computer and is never uploaded.
Worked example
One cause, two diagnostics
In the first version of this program, the line let total = 0; read let total = "0";. tsc then reported main.ts(6,25): error TS2362 for total * 1.19 and main.ts(8,29): error TS2551 for total.toFixed(2), with Did you mean 'fixed'?. Neither pointed at the declaration, and total += price was accepted, because adding a number to text is allowed. Changing "0" to 0 fixed both. Run npx tsc, which prints nothing, then node main.ts. Then put the quotes back and read both diagnostics yourself.
main.ts
const prices: number[] = [3.5, 4.25, 2];
let total = 0;
for (const price of prices) {
total += price;
}
const withTax: number = total * 1.19;
console.log("items:", prices.length);
console.log("total:", total.toFixed(2));
console.log("with tax:", withTax.toFixed(2));
Run it with
npx tsc
node main.tsOutput
items: 3
total: 9.75
with tax: 11.60- The positions in the intro are this file's: line 6 holds the multiplication, line 8 the toFixed call, and line 2 the cause.
- total += price type-checks even when total is text, so the first error appears later, at the multiplication.
- The suggestion 'fixed' is a real string method, but calling it would not print a number with two decimals.
- tsc printing nothing is the signal to run node main.ts.
Change it and run it
Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.
The first run downloads the TypeScript compiler (up to 2.1 MB) and keeps it cached. Your code stays on your device.
Exercises
Exercise 1 of 2
Work down the list
This program should print Kitchen has 7 letters, then Floors: 1, then Area: 12 m2 (the room is 4 by 3 metres). tsc reports three errors. Run the tests or npx tsc, fix the first diagnostic, run again, and continue until the type-check passes. Change only what the diagnostics point to.
Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.
The first run downloads the TypeScript compiler (up to 2.1 MB) and keeps it cached. Your code stays on your device.
Hints
Hint 1
The first diagnostic is main.ts(6,7): error TS2322: Type 'string' is not assignable to type 'number'. "1" in quotes is text.
Hint 2
The second one ends with Did you mean 'length'? Here the suggestion is right.
Hint 3
Expected 2 arguments, but got 1. means area needs the height too: area(4, 3).
Show a solution
One way to solve it. Yours can look different and still pass the checks.
function area(width: number, height: number): number {
return width * height;
}
let room = "Kitchen";
const floors: number = 1;
console.log(room, "has", room.length, "letters");
console.log("Floors:", floors);
console.log("Area:", area(4, 3), "m2");
Run it on your computer
Install TypeScript 7.0 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.
main.ts
function area(width: number, height: number): number {
return width * height;
}
let room = "Kitchen";
const floors: number = "1";
console.log(room, "has", room.lenght, "letters");
console.log("Floors:", floors);
console.log("Area:", area(4), "m2");
main.test.ts
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {runMain} from './learnrun.js';
test('the program prints the three lines', async () => {
const out = (await runMain()).trimEnd();
assert.equal(out, 'Kitchen has 7 letters\nFloors: 1\nArea: 12 m2', `the program printed ${JSON.stringify(out)}`);
});
test('the area line uses both sides of the room', async () => {
const out = await runMain();
assert.match(out, /Area: 12 m2/, 'the last line should be Area: 12 m2');
});
package.json
{
"type": "module"
}
tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"module": "nodenext",
"lib": [
"esnext",
"dom"
],
"types": [],
"strict": true,
"noEmit": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true,
"allowImportingTsExtensions": true
},
"include": [
"**/*.ts"
],
"exclude": [
"**/*.test.ts"
]
}
npx tsc needs TypeScript in the folder: run npm install --save-dev typescript there once. tsc checks the types; Node.js runs main.ts by removing them.
Run the program:
npx tsc
node main.tsRun the checks (needs learnrun.js in the same folder):
npx tsc
node --testDownload learnrun.jsExercise 2 of 2
Fix the cause, not the symptom
This program should print Total: 8 and Average: 2.7. It prints Total: 0251 and Average: 83.7, and tsc reports one error, on line 6. Wrapping count in Number() on line 6 silences tsc, but the output stays wrong. Find the line that makes count text, fix it there, and check that tsc and the tests pass.
Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.
The first run downloads the TypeScript compiler (up to 2.1 MB) and keeps it cached. Your code stays on your device.
Hints
Hint 1
The diagnostic is main.ts(6,25): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. The left-hand side is count.
Hint 2
Why is count not a number? Look at where it gets its first value.
Hint 3
On line 1, "0" in quotes makes count a string, so count + n joins text. Write let count = 0;.
Show a solution
One way to solve it. Yours can look different and still pass the checks.
let count = 0;
const items = [2, 5, 1];
for (const n of items) {
count = count + n;
}
const average: number = count / items.length;
console.log("Total:", count);
console.log("Average:", average.toFixed(1));
Run it on your computer
Install TypeScript 7.0 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.
main.ts
let count = "0";
const items = [2, 5, 1];
for (const n of items) {
count = count + n;
}
const average: number = count / items.length;
console.log("Total:", count);
console.log("Average:", average.toFixed(1));
main.test.ts
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {runMain} from './learnrun.js';
test('the total is 8', async () => {
const out = await runMain();
assert.match(out, /^Total: 8$/m, `expected the line Total: 8, the program printed ${JSON.stringify(out)}`);
});
test('the average is 2.7', async () => {
const out = await runMain();
assert.match(out, /^Average: 2\.7$/m, `expected the line Average: 2.7, the program printed ${JSON.stringify(out)}`);
});
package.json
{
"type": "module"
}
tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"module": "nodenext",
"lib": [
"esnext",
"dom"
],
"types": [],
"strict": true,
"noEmit": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true,
"allowImportingTsExtensions": true
},
"include": [
"**/*.ts"
],
"exclude": [
"**/*.test.ts"
]
}
npx tsc needs TypeScript in the folder: run npm install --save-dev typescript there once. tsc checks the types; Node.js runs main.ts by removing them.
Run the program:
npx tsc
node main.tsRun the checks (needs learnrun.js in the same folder):
npx tsc
node --testDownload learnrun.jsCommon mistakes
Accepting a "Did you mean" that does not fit
const prices: number[] = [3.5, 4.25, 2];
let total = "0";
for (const price of prices) {
total += price;
}
const withTax: number = total * 1.19;
console.log("items:", prices.length);
console.log("total:", total.toFixed(2));
console.log("with tax:", withTax.toFixed(2));
What tsc or Node.js prints
main.ts(8,29): error TS2551: Property 'toFixed' does not exist on type 'string'. Did you mean 'fixed'?Why, and the fix
tsc suggests a string method with a similar name, because total is a string. Renaming toFixed to fixed would type-check on that line and print text wrapped in <tt> tags instead of 9.75. Read the type in the message first: on type 'string' tells you total should not be a string at all. The cause is line 2: write let total = 0;, and both errors, on lines 6 and 8, disappear.
Looking for type errors behind a syntax error
const count: number = "3";
console.log("count is", count;
const label: string = 5;
What tsc or Node.js prints
main.ts(2,30): error TS1005: ')' expected.Why, and the fix
While a bracket is missing, tsc cannot read the file, so it reports only the syntax error and says nothing about types. It does not mean lines 1 and 3 are fine. Add the ) at line 2, column 30, run npx tsc again, and then fix the two type errors that appear: count gets 3 without quotes, and label gets "5" or a different type.
Calling a function with an argument missing
function area(width: number, height: number): number {
return width * height;
}
console.log(area(3));
What tsc or Node.js prints
main.ts(4,13): error TS2554: Expected 2 arguments, but got 1.Why, and the fix
In JavaScript, a missing argument quietly becomes undefined, and 3 * undefined prints NaN. TypeScript counts the arguments against the parameters and reports the call. Column 13 is where area starts. Pass both values: area(3, 4).
TypeScript in the browser: the TypeScript 6.0.3 compiler, Apache-2.0, then your browser’s own engine. Licence and source
Exit ticket
5 questions, no hints. Score 80% or more to complete the lesson.
Finish every activity above to unlock the exit ticket.