TypeScript for Real Projects · 26 min · 180 XP

Strict checks and type regression tests

Use strict compiler checks, negative type tests and runtime tests as complementary feedback.

Runtime tests execute selected inputs. Compiler checks examine whether typed operations obey their declared contracts, without executing the program. A transpiler can remove types even when those contracts are wrong. Use both checks: a correctly typed function can still return the wrong calculation, and correct output on a few examples does not prove a useful generic signature.

A small standalone practice tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "noEmit": true,
    "types": []
  },
  "include": ["practice.ts"]
}

In a new practice directory, run npm init -y, then npm install --save-dev typescript. Save this config as tsconfig.json, copy one exercise into practice.ts, and run npx tsc -p tsconfig.json. Keep each exercise in its own module with export {} if you split it into files. In an existing app, use its framework's module settings. strict enables strictNullChecks and noImplicitAny; the two additional flags above must be enabled separately.

An intentional error checks that the public contract stays narrow
function double(value: number): number { return value * 2; }
const amount: number = double(4);
// @ts-expect-error: text is not an accepted input
double("4");

If double accidentally accepts any, the expected-error directive becomes unused and the compiler reports it. Keep these negative tests in a type-check-only file; the directive does not stop code from executing. First read the earliest diagnostic, fix the incorrect assumption at its source, then rerun the checker. Do not blanket-suppress errors with any, assertions or ts-ignore. Readonly is shallow compile-time protection; use copying or freezing when runtime mutation matters.

Local lab: after solving the challenge, enable the config above. Verify a number assignment from selectField({ score: 5 }, 'score') passes. Add an @ts-expect-error call using a missing key, then temporarily loosen the signature to any and confirm the directive becomes unused. Restore the generic signature. Official references: narrowing, generics, and checked indexing.

Loading your workspace…