← Fundamentals
Fundamentals

Static and dynamic type checks

Which checks happen before execution, and which depend on a running value?

Separate source-type guarantees, runtime checks, and the policy for imported values.

Outcome

Explain what the selected source checker establishes, identify the shown runtime checks, and validate outside values against the importer’s policy.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Static check
Analysis of source against the selected language rules before execution; the shown ordinary runtime branches are included.
Dynamic check
A check of values or an operation while the program runs.
Type assertion
An operation that states or checks an expected type; its effect depends on the native language and form used.
Parse
Convert text into a value under a particular grammar, with the conversion’s own success/failure behavior.
Bounds check
Establish that an index lies in the collection’s valid range.

Three places to establish a guarantee

Static checking reasons about source before execution, using declared and inferred types. Runtime checks inspect an operation or value during execution. A program can pass its source checker and still encounter an out-of-range index or outside data that does not satisfy its assumptions.

Application validation adds the rules for acceptable input: its shape, token format and allowed range. Establish which layer checks each requirement and how failure is represented. A converted number alone may not carry enough information to decide whether an import succeeded.

01Before the run

Check a branch this run does not take

A rail reservation importer totals passenger-count requests, combines boarding counts with operational notes, and answers berth-number lookups. Zero can clear a request; malformed count text must be reported as skipped. Before repairing those entry points, the team needs to establish which mistakes its checker catches and which require inspecting a running value.

The boarding announcement helper has a special branch for waits over 60 minutes. The call supplies 15 minutes. Inspect both branches and predict the result of the selected check/build-and-run command.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
function boardingText(gate: string, minutes: number): string {
  if (minutes > 60) {
    return "Gate " + gate.toFixed(0);
  }

  return `Gate ${gate} in ${minutes} minutes`;
}

console.log(boardingText("B4", 15));
What happens?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc main.ts --noEmit --strict --skipLibCheck --target es2022 --module nodenext --types node && node main.ts

Save one complete example at a time under the selected filename, using the language setup from the first reading. The shown command runs only after its check/build step succeeds. Predict that result before executing the example.

02While it runs

An outside index needs a runtime policy

The lookup probe reads gate 1 and then gate 3 from a three-element list. Compare the operations shown in the selected native; they need not fail at the same point.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const gates = ["A1", "B2", "C3"];

console.log(gates[1]);
const gate = gates[3];

console.log(gate);
console.log(gate.toLowerCase());
What happens?

03Values from outside

A declared type does not validate an imported value

A transport seat count arrives as text or JSON. Each probe uses its selected conversion or assertion, then reports the result. Predict what the operation actually establishes.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type Flight = { code: string; seats: number };

const flight = JSON.parse('{"code": "NT7", "seats": "155"}') as Flight;

console.log(flight.seats + 1);
What is printed?

04Where to check

Carry conversion success separately from the count

parsePassengers reports results for the literal strings 12, x and 0. Predict those lines, including the valid zero. These are conversion probes; the import file’s complete token format is a separate requirement.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
function parsePassengers(text: string): number | undefined {
  const passengers = Number(text);

  return Number.isInteger(passengers) && passengers >= 0 ? passengers : undefined;
}

for (const text of ["12", "x", "0"]) {
  const passengers = parsePassengers(text);

  console.log(passengers === undefined ? `${text}: invalid` : `${text}: ${passengers}`);
}
What is printed?

05Repair the rail reservation importer

Passenger requests, boarding records, then berth lookup

Total passenger-count requests in the reservation file, count malformed count tokens as skipped, and keep zero as a real value. The existing file format is one nonempty ASCII digit token: leading zeros are valid, while signs, fractions and numeric prefixes are not.

Then combine typed boarding-count records while leaving operational notes out of the total. Finally answer signed one-based berth requests against the supplied manifest. Complete readers and callers are supplied; notes and missing berths require their own policy.

Repair the rail reservation importer

Validate a complete count token, distinguish a boarding entry’s kind, then check signed requests against existing berths.

  1. easy · F-TYPE-V4-1 Total passenger requests
  2. medium · F-TYPE-V4-2 Count the train riders
  3. hard · F-TYPE-V4-3 Show the night-train berths
In the frontend A typed component can still hold an unconverted form string. Optional

The import screen keeps the count text exactly as typed until its submission boundary applies the file-format policy. Giving the parent or component a TypeScript type does not change the runtime value supplied by a text input.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
'use client';

import { useState } from 'react';

export function CountText() {
  const [text, setText] = useState('0');

  return (
    <label>
      Passenger request
      <input
        type="text"
        value={text}
        onChange={(event) => setText(event.target.value)}
      />
      <output>{text.length} UTF-16 code units</output>
    </label>
  );
}

The input event supplies a string, and the setter retains that string for a subsequent render. Starting with "0" does not make later input a number or establish the request format.

Sources: React: input value,Svelte: input bindings.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.