Choosing the Strict Flags

Both of door-check’s TypeScript configuration files now set "strict": true, and npm run check passes. Suppose you’re drafting the code behind the page’s search box, where an usher types a booking reference and the page shows that party. A quick draft of that JavaScript works on a good night and breaks on a bad one, such as when someone gives a reference that isn’t on the list. Does that one "strict" line catch slips like these?

In this lesson, you’ll see what the checks inside strict catch, meet the flags beyond it that many teams add, and choose the ones door-check needs. You’ll come back to this when you turn strictness on in a project that doesn’t have it yet. Start with a quick draft and see what strict says about it.

Look Inside strict

A first draft is where slips hide, so it’s a good test of what strict checks. Create a scratch file, src/try-flags.ts, in door-check. It’s an experiment that you’ll delete later. It contains the kind of JavaScript you might write for the search box. There’s a function that formats a party, a lookup for a reference nobody booked, and a try block that parses a saved door list, broken here on purpose:

Language: TypeScript Filename: src/try-flags.ts
 1import { doorList } from "./door-list.ts";
 2
 3function partyLine(booking) {
 4  return `${booking.name}, party of ${booking.partySize}`;
 5}
 6
 7const found = doorList.find(
 8  (booking) => booking.reference === "LST-0499",
 9);
10console.log(found.name);
11
12try {
13  JSON.parse("{ not a door list");
14} catch (error) {
15  console.log(error.message);
16}

The root tsconfig.json includes everything in src/, so the check reads the new file. Run it from the project folder:

Language: Shell
$ npm run check

> [email protected] check
> tsc --noEmit -p tsconfig.json && tsc --noEmit -p scripts/tsconfig.json

src/try-flags.ts:3:20 - error TS7006: Parameter 'booking' implicitly has an 'any' type.

3 function partyLine(booking) {
                     ~~~~~~~

src/try-flags.ts:10:13 - error TS18048: 'found' is possibly 'undefined'.

10 console.log(found.name);
               ~~~~~

src/try-flags.ts:15:15 - error TS18046: 'error' is of type 'unknown'.

15   console.log(error.message);
                 ~~~~~

Found 3 errors in the same file, starting at: src/try-flags.ts:3

Each of the three errors comes from a different check, because strict is a shortcut. "strict": true turns on a whole family of strict flags at once, compiler options that each report one kind of risky code. The three in your draft catch most of the errors in a project like door-check:

  • noImplicitAny reports a parameter whose type the checker can’t work out, instead of quietly giving it the type any. That’s TS7006, because nothing tells the checker what partyLine() receives.
  • strictNullChecks keeps null and undefined out of every type that doesn’t list them. That’s TS18048. .find() can find nothing, so the type of its result includes undefined, and the checker reports found.name whatever the list holds. Here nothing matches "LST-0499", so this line would also crash when it runs.
  • useUnknownInCatchVariables gives the error in a catch block the type unknown. That’s TS18046, because a throw can send a string or a number as well as an Error, so the checker can’t promise that error has a .message.

The others catch rarer slips. For example, strictPropertyInitialization checks for class properties that constructors never set, and strictBindCallApply checks for wrong arguments to .call().

Why call them separate flags if strict turns them on together? Each flag has its own name, and a flag you set yourself wins over strict. You can confirm this. Add one line under "strict": true in the root tsconfig.json:

Language: JSON Filename: tsconfig.json
    "strict": true,
    "useUnknownInCatchVariables": false,

Run npm run check again. The catch error is gone, and the other two stay:

Language: Shell
$ npm run check

> [email protected] check
> tsc --noEmit -p tsconfig.json && tsc --noEmit -p scripts/tsconfig.json

src/try-flags.ts:3:20 - error TS7006: Parameter 'booking' implicitly has an 'any' type.

3 function partyLine(booking) {
                     ~~~~~~~

src/try-flags.ts:10:13 - error TS18048: 'found' is possibly 'undefined'.

10 console.log(found.name);
               ~~~~~

Found 2 errors in the same file, starting at: src/try-flags.ts:3

Turning the flag off didn’t fix the code. Now error has the type any, so the checker lets you read anything from it. Line 15 still reads .message from a value that might not have one, and the checker has only stopped saying so. That’s why a project keeps strict on. A flag switched off to quiet an error leaves the bug for runtime to find. Delete the line you added and the scratch file, so door-check is back to full strict.

The flags change only what the checker reports. The JavaScript that runs is the same whichever flags you set.

Look Past strict

Even full strict trusts some code that can go wrong. TypeScript has more flags that strict leaves out, because they also report code that’s often fine and ask you to write extra checks for it. Two of them are on in the template that npx tsc --init writes, under a comment that calls them stricter typechecking options:

Language: JSON
    // Stricter Typechecking Options
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,

noUncheckedIndexedAccess adds undefined to the type of a value you read by index, such as doorList[0]. It asks you to handle the case where nothing is there, as strictNullChecks does for .find().

exactOptionalPropertyTypes makes an optional property mean “may be missing” and nothing more. Normally, a booking type with note?: string accepts a booking without a note and also one with note: undefined. With the flag on, the checker rejects the second one, because "note" in booking is true for it. That difference matters when code tests for a property with in.

noImplicitOverride is in the template too, but commented out. It applies to classes. When a child class replaces a method from its parent class, the child’s method must say override. Then, if someone renames the method in the parent, the checker reports the leftover method in the child.

Choose Door-Check’s Flags

Choosing flags means asking what the project’s code does. These defaults suit most new projects:

  • Keep strict on, even when it reports errors. Each error points to code you need to fix.
  • Add noUncheckedIndexedAccess when code reads arrays or records by index or by position.
  • Add exactOptionalPropertyTypes when code tells a missing property apart from one set to undefined.
  • Add noImplicitOverride when the project has classes that extend other classes.

Since you can set flags individually, an existing project that can’t pass all of strict yet can start with "strict": false and turn the flags on one at a time. You’ll do exactly that with the theater’s ticketing pages later in this course.

Door-check’s page will read the door list by position too. The file src/door-list.ts already defines the Booking type that doorList uses, so add these two lookups to its end, below doorList. firstArrival() gives the ushers the name at the top of the list, and bookingAt() gives the booking on a numbered line of the printed list, counting from 1:

Language: TypeScript Filename: src/door-list.ts
export function firstArrival(list: Booking[]): string {
  const first = list[0];
  return first.name;
}

export function bookingAt(list: Booking[], line: number): Booking {
  return list[line - 1];
}

Door-check doesn’t extend classes, and its bookings don’t tell a missing property apart from an undefined one, but its code reads the door list by position. So noUncheckedIndexedAccess is the flag it needs. Add it under "strict": true in both tsconfig.json and scripts/tsconfig.json, since the export script imports the same door list:

Language: JSON Filename: tsconfig.json
    "strict": true,
    "noUncheckedIndexedAccess": true,

Run npm run check. It now reports two errors in src/door-list.ts, one in each lookup: TS18048 in firstArrival() and TS2322 in bookingAt(). The page code’s check fails first, so && stops before the script’s check runs.

Leave both errors in place for now. In the next exercise, you’ll work out why the flag reports them and what the ushers should see instead.

Want to practice choosing flags for a project?

Check Your Understanding

  1. For each snippet, which strict flag reports an error?
  2. (a) function refund(amount) {
  3. (b) catch (error) { console.log(error.message); }
  4. (c) const left = seatsLeft.get("The Tempest"); followed by left - 1, where seatsLeft is a Map of shows to seat counts
  5. A teammate turns off strictNullChecks because it reports forty errors in their code. Is the code safer now? What would you suggest instead?
  6. Mei Chen, who runs the box office, wants a new page that lists each performance’s sold seats from an array and reads them by position. Which flags would you set in its tsconfig.json, and why?

For question 1, (a) is noImplicitAny, since nothing says what amount holds. (b) is useUnknownInCatchVariables, since error is unknown. (c) is strictNullChecks, since .get() returns number | undefined and the check reports 'left' is possibly 'undefined'.

For question 2, the code is no safer. The forty places where a value might be null or undefined are still there, and the checker has only stopped reporting them. Keep the flag on and work through the errors, or turn it on again as soon as the code is ready.

For question 3, keep strict on and add noUncheckedIndexedAccess, because a lookup by position can return undefined. Add exactOptionalPropertyTypes only if the page tells a missing property apart from an undefined one, and noImplicitOverride only if it has classes that extend other classes.

You can now say what strict turns on and choose the flags beyond it that a project needs. Next, in Exercise: Fix the Door-List Lookups, you’ll make door-check’s two lookups give the ushers a useful answer on any night. It’s the course’s first coding exercise. You write and run the code in your browser, and the exercise’s Contents tab explains how the tests work.

Become a Member to join the conversation.