Boss lesson · Unit 04
A Strict Project
Move a JavaScript file to strict TypeScript, one error at a time
What you practise
tsconfigand whatstrictturns on, modules and declaration files, typing a library that has no types, moving a JavaScript file to TypeScript one error at a time
Try a question from this lesson
Pick one
This file ran fine as cart.js. You rename it to cart.ts with strict on. Where is the only error?
function total(items) {
let sum = 0;
for (const it of items) sum += it.price;
return sum;
}Correct answer
Line 1: items has no type
Why
An unannotated parameter is an implicit any, and strict refuses those. sum is inferred as number from its value, and the return type from the return. Line 3 is not flagged: it comes out of an any, and any allows anything.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
tsconfig and strict
A project is configured by tsconfig.json at its root. strict is not one check but a family switched on together. The two that matter most: noImplicitAny (a type the compiler cannot work out must be written) and strictNullChecks (null and undefined must be handled).
include says which files belong to the project. With noEmit the compiler only checks, and another tool produces the JavaScript.
{
"compilerOptions": {
"strict": true,
"noEmit": true
},
"include": ["src"]
}Concept
Modules and declarations
Types cross files with the same import and export as values, and import type brings in a type only.
A plain JavaScript library has no types to import. A declaration file, name.d.ts, supplies them: signatures with no bodies, introduced by declare. It produces no code. It is a promise about what exists at run time and, like as, nobody checks the promise.
// cart.ts
import type { Item } from "./item";
import { clamp } from "legacy-math";
// legacy-math.d.ts
declare module "legacy-math" {
export function clamp(
n: number, lo: number, hi: number,
): number;
}10 more exercises in the app
- 1× match the pairs
- 3× fill the blanks
- 3× multiple choice
- 2× type the answer
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.