Bitpath

Boss lesson · Unit 04

A Strict Project

Move a JavaScript file to strict TypeScript, one error at a time

13 exercisesabout 3 min

What you practise

  • tsconfig and what strict turns 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?

TypeScript
function total(items) {
  let sum = 0;
  for (const it of items) sum += it.price;
  return sum;
}

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.

JSON
{
  "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.

TypeScript
// 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.

One email when Bitpath is ready to try. Nothing else. Privacy