A tutorial
Change code so its types catch more mistakes
Start with the five mistakes below, then compare the proposed changes and their checks. Each new concept appears with its example. These are code-change lessons; a passing type checker does not replace behavior tests or a Lean proof of a stated property.
1. The program we will fix
The example is a bicycle invoicing program. It stores product IDs, customer IDs, prices, quantities and invoice states. Its untyped functions accept values in the wrong slots, so a call can run while producing the wrong invoice.
Every code cell is editable. In the first cell, print bill("roadster", "Mrs. Pemberton") and press Run. The swapped customer and product arguments produce an invoice addressed to the product. The following sections add types and checks that distinguish those roles.
That's one of five mistakes waiting in the file:
- Unchecked argument types let mismatched values reach
invoice_line. - Prices are plain numbers, and some functions count in pence while others count in pounds.
advancecompares the status againstdarft, so no invoice leaves the draft state and no customer gets billed.- Customer and product IDs share an unmarked type, so a checker cannot distinguish the swapped call to
bill. load_bom_linepasses every field on as text, quantities and prices included.
Press Type check on the starting program. Python's ty accepts its unannotated functions, while TypeScript's tsc --strict reports implicit any parameters. Neither result identifies all five application mistakes. Gradual typing allows unchecked parts alongside checked code; follow each change to see which mistake it catches.
2. Simple types
Start with invoice_line. A parameter is a named slot for an argument. This function needs text for a description, integers for price and quantity, and a boolean tax flag. Distinguishing those types catches some swapped arguments.
Annotate the parameters with str, int and bool. Put a price in the description slot and ask the checker again. It reports the mismatched types. Price and quantity are both integers, so swapping those two still needs distinct units or a behavior test. Annotations do not add automatic runtime validation.
A price and a discount rate can both be numbers while meaning different things. In the next example, reversing the arguments to apply_discount produces the wrong amount. The function needs types that distinguish these roles.
Define distinct Pence and Rate types, then try the reversed call. The type checker reports a mismatch. TypeScript removes these type labels from generated JavaScript. Python's NewType constructor still runs and returns the supplied value; this page does not measure its cost.
A gift note can be text or missing: str | None describes those two possibilities. A cast tells the checker to trust you without checking the value. Casting a missing note to text therefore cannot prevent a runtime failure.
Check note is None and return before calling the text method. On the remaining path, the checker can treat the note as text. This is narrowing: a condition reduces the possible types at that point. The condition also executes when the program runs.
3. Aliases and units
The parts file measures spokes by count and tubing by length. An alias gives an existing type another name; it does not create a distinct unit. A Meters alias for a number therefore still accepts a spoke count.
Use Python's NewType or a TypeScript brand to distinguish units during checking. A brand is a type label added to an otherwise ordinary value. Pass a spoke count to cut_tubing and inspect the type error. Runtime input checks must still establish that outside values have the promised units.
Watch the arithmetic, though. Add two branded lengths and the sum comes back a plain number, brand gone.
Define operations for the units: adding two lengths returns a length, while multiplying them returns an area. The example uses objects to hold those values, so construction and arithmetic allocate objects. Measure the actual workload before judging that runtime cost.
A plain string allows the misspelling darft wherever draft was intended. The next change restricts an invoice status to the three supported values.
List the supported statuses in the type, then try darft and press Type check. The checker rejects it. Literal types restrict checked code; input arriving as text still needs runtime validation.
4. Domain types
A customer email field can contain an empty string, surrounding spaces or text without @. Checking it once but returning an ordinary string loses the distinction between checked and unchecked text.
Return EmailAddress from parse_email and require it in send_receipt. This is a domain type: a type representing a rule of the application. Keep construction with the check, because a cast can otherwise claim the rule without enforcing it. The validation still runs; the label alone does not validate an address.
A customer ID and a product ID can both be strings. Giving them distinct types lets the checker distinguish the argument slots that were swapped in the first section.
Give each ID a distinct type and repeat the reversed call. The checker reports the mismatch. Outside strings still need the appropriate conversion, and casts can bypass the distinction.
Escaping replaces characters so text can be inserted into an HTML context. Returning an ordinary string loses the record of that operation, allowing callers to escape it twice.
Return HtmlText from the escaper and require it in this renderer. The checked signatures distinguish raw text from the example's escaped text. The wrapper allocates a value. This does not establish safety for every HTML, URL or script context.
The shipping code needs a carrier with a quote_pence method. Another package can provide that method without inheriting our carrier class. The next example describes the required methods so the checker can recognize that object.
Declare a Protocol and Python matches shapes too: the outside class counts as it stands, with no inheritance asked for. A Protocol exists for the checker alone unless you mark it runtime-checkable.
5. States and stages
A payment with a boolean settled flag and an optional receipt allows a contradictory combination: settled with no receipt. Describe pending and settled payments as different shapes so checked construction must supply the right fields.
Give Settled a required receipt field and Pending no receipt. Try constructing a settled payment without its receipt and inspect the error. These are tagged states: the program distinguishes which shape it holds before reading its fields.
An invoice should be sent before it can be paid. A comment leaves every caller responsible for remembering that order. Distinct stage types can make the permitted order part of the function signatures.
Let send return SentInvoice and require that type in record_payment. Try passing a draft and inspect the type error. This pattern is called typestate: the available operations depend on the represented stage. The example's transitions also create runtime objects.
6. At the border
Command-line arguments arrive as text. If each function receives a dictionary of strings, it must check again whether the port is numeric and within range. The dictionary's type does not record that a prior check succeeded.
Validate the port in parse_argv and return Config. Functions that accept this checked shape can use its numeric port. Keep untrusted construction at that boundary, the point where outside input enters the application.
The type records the validation performed on the input. It cannot reserve a network port or ensure another process will leave it available. Opening the connection still needs its own error handling.
A general JSON value can be a number, text, a list, an object or null. Passing that broad shape through every function forces each reader to check its fields again. Convert it into the application's required fields before doing invoice arithmetic.
Validate each decoded line and return Line. Downstream code can then read line.pence without asserting its type through a cast. JSON decoding only reads the data format. Neither json.loads nor JSON.parse establishes the application's required fields and types.
An external configuration can describe servers and databases with one generic bag of attributes. That shape permits misspelled keys and missing fields. Define the distinct settings your own program requires, and validate the external data when importing it.
Model the fields this application uses and reject invalid input during conversion. Ask what a proposed type rules out. A broad shape that accepts the same invalid combinations leaves the original behavior checks necessary.
7. Functions as values
The picking list takes a function that chooses a sorting key. This is a callback: a function supplied for another function to call. Its declared argument and result types should describe invoice lines and the keys the sort expects.
Declare what the callback accepts and returns. Pass a callback requiring a different input and ask the checker to identify the mismatch. The declared type adds a check before execution; the program still performs the same callback call.
Take the handler table next, one handler per order status.
A handler table maps each supported status to a function. Declare the argument and result types those functions must share. Try an incompatible handler and inspect the reported mismatch. Runtime dispatch remains a lookup followed by a call.
A retry helper receives a function and returns a wrapped function. Giving both the broadest possible type loses the original argument checks. The next change preserves the wrapped function's signature.
Preserve the argument and return types through the wrapper, then try a call with an invalid argument. The checker should still report it. The wrapper itself executes and adds a function call each time it is used.
8. Composition and monads
The next examples chain operations that can have several answers, no answer or a delayed answer:
- a comprehension that flattens a list of lists,
await, which unwraps an answer that arrives later,- the
ifthat clears away a value that may be missing.
A common design puts a value inside a container and provides a way to chain the next operation. A monad is that design with rules for consistent chaining. The examples illustrate the idea; they do not prove those rules. Introduce each container by the problem it handles:
- Option: the answer may be missing. Neither language ships it;
| Noneand optional chaining cover it. - Result: the step failed, and the reason matters.
- Promise: the answer arrives later; chain it with
await.
Use the language's ordinary operations when they fit: missing-value checks, exceptions, comprehensions and await. Here, quote has three distinct failures: invalid quantity, insufficient stock and missing price. Returning None for all three loses the reason.
Return Ok with the price or Err with a failure reason. The example's and_then calls the next step only after success and carries a failure forward unchanged. This makes the result and failure cases visible to the caller. Each step can allocate a wrapper; no runtime benchmark is recorded here.
A function is pure when its result depends on its arguments and it has no outside effects. Its ordinary type signature alone does not establish that property. Reading the clock inside remaining makes the result depend on when it runs.
Pass the current time as now. A test can then choose a fixed time and check a thirty-minute result. Inspect the implementation too: accepting the argument alone cannot establish that the function has no other effects.
9. Exercises
Exercise 1: make the typo impossible
The misspelled status prevents one branch of advance from running. Restrict the status type and require a case for every supported status.
Hint
Section 3 for the literal type. Section 5 for an exhaustive match with
assert_never, or a switch with a never
default.
Exercise 2: name the units and the flags
Two call sites disagree about the argument order, and both run. A row of bare booleans at a call site tells the reader nothing. Give the units types and the flags names.
Hint
Section 3 for the units. For the flags, use a frozen dataclass or an object type with named fields.
Exercise 3: parse the user once
The user record arrives as JSON and travels on as a loose dictionary, so every function re-checks the fields before using them. Write one parse at the edge, then delete the checks downstream.
Hint
Section 6. Write one parse function that returns a User or
raises, call it in summary, and let the field types travel.
Exercise 4: separate the currencies
A plain numeric amount does not distinguish dollars from euros. Give the currencies distinct types and check that adding them produces a type error.
Hint
In Python, write one class per currency and a constrained type variable,
[M: (Usd, Eur)]. In TypeScript, take a generic currency parameter and
wrap the second argument in NoInfer, which pins the currency to the first amount.
Exercise 5: give each failure its reason
Three lookups can each fail, and all three collapse into one None. Rebuild the chain on Result.
Hint
Section 8. Write three small functions returning Result, and thread
them with and_then.
10. The concepts
Every idea the page used, and the name people call it by. Read the third column if you read nothing else: most of this exists for the checker alone and disappears the moment your program starts.
| Concept | What it means | Scan or run time | Section |
|---|---|---|---|
| Gradual typing | Checked and unchecked code in one program, with Any as the seam. | Scan only | 2 |
Any | The escape hatch: every value fits, and the checker stops looking. | Neither; it turns the checker off | 2 |
| Stringly typed | Strings carry the meaning, where no checker can read it. | Neither; the checker sees a string | 2 |
| Narrowing | The checker follows a test and uses the narrower type inside the branch. | Scan, and the test itself runs | 2 |
| Type alias | A second name for the same type. It enforces nothing. | Scan only; nothing survives | 3 |
NewType, brand | A distinct type over the same representation. | Scan only; the plain value remains | 3 |
| Literal type | The values that exist, written into the type itself. | Scan only; plain strings at run time | 3 |
| Units of measure | Quantities that must never mix; their types keep them apart. | Scan only | 3 |
| Domain type | A type that states a fact about your problem. | Scan; a class also exists at run time | 4 |
| Primitive obsession | Building everything out of raw strings and numbers. Scott Wlaschin's name for it. | Neither; the checker sees int and str | 4 |
| Smart constructor | The one function that may build the type, holding its invariant. | Both; the check runs, the type records it | 4 |
| Structural and nominal typing | Anything with the right shape fits, against only the declared name fits. | Scan only | 4 |
Protocol | Python's opt-in structural typing: the methods a value must have, no inheritance. | Scan only, unless marked runtime-checkable | 4 |
| Tagged union | One of several shapes, and the tag tells them apart. TypeScript calls it a discriminated union. | Scan; the tag field is real data | 5 |
| Illegal states unrepresentable | Reshape the data so the bad combination can't exist. Yaron Minsky's phrase. | Scan only | 5 |
| Exhaustiveness checking | Every reader must handle every case, or the check fails. | Scan, with a throw as the net beneath | 5 |
| Typestate | The type carries the value's stage, so a step out of order is a type error. Rust named it. | Scan only; the objects are ordinary | 5 |
| Validation | Check a value and pass the same value on. Nothing records that the check ran. | Run time, and again at every reader | 6 |
| Parsing | Run the same check and return a different type, which every later function demands. | Both; runs once, holds ever after | 6 |
| Shotgun parsing | Every reader repeats the same check, and malformed input slips between them. | Run time, repeatedly | 6 |
| Parse, don't validate | Alexis King's rule: convert at the border, then write functions on the data you wish you had. | Both, by design | 6 |
| Fake type | A type wide enough to hold whatever the source can hold. It spreads through every signature and rules nothing out. | Scan only, and it holds nothing back | 6 |
| Higher-order function | A function that takes or returns a function. | Both; real values the checker types | 7 |
| Signature preservation | A wrapper that keeps the wrapped function's exact type. | Scan only | 7 |
| Monad | A wrapper with a way in and a chaining step that returns the wrapper. | Both; real values, checked chains | 8 |
| Railway-oriented programming | Scott Wlaschin's picture of a Result chain: two tracks, one switch. | Both | 8 |
| Purity | Same arguments, same result, nothing else. Formally, referential transparency. | Neither; a discipline the checker can't see | 8 |
| Dependency injection | Hand a function what it needs instead of letting it reach out. | Both; a real argument with a type | 8 |
| Boolean blindness | A row of bare booleans at a call site tells the reader nothing. Robert Harper's term. | Neither; every bool fits | 9 |
11. The toolbox, compared
Which construct to reach for, and what it buys. Everything here needs Python 3.12 or TypeScript 5.4. Python checking remains gradual when a function has no annotations, and tsc trusts array indexing until you turn on noUncheckedIndexedAccess, which this page does.
Python
| Construct | The checker holds | At run time, and what it costs | Reach for it when | Since |
|---|---|---|---|---|
type alias | Nothing; the same type under a new name | The alias object can exist in Python; it adds no automatic value validation | A long signature needs a short, honest name | 3.12 as the type statement |
NewType | The label: Meters can't go where Pence belongs | The constructor runs and returns the supplied value | Two same-shaped values must never swap | 3.5 |
Literal | A closed set of values | Plain strings and numbers, so nothing to pay | A field or flag has a fixed menu | 3.8 |
Enum, StrEnum | A closed set with a named member for each value | A runtime member object; construction and lookup execute | The set must also exist at run time, as when parsing a CSV column | 3.4; StrEnum 3.11 |
@dataclass(frozen=True) | The shape: field names and types | Object construction runs; frozen fields reject ordinary reassignment | Data with named fields, which is most data | 3.7 |
NamedTuple | The shape, like a dataclass | A tuple instance; construction, indexing and unpacking execute | You need tuple compatibility; otherwise a dataclass reads better | 3.6 |
TypedDict | The keys and value types of a dictionary | A plain dictionary; the type declaration does not validate its contents | Dictionaries you can't replace, like JSON already flowing through code | 3.8 |
Union of dataclasses + match | Exhaustiveness: every reader handles every state | Ordinary objects; the match costs one tag comparison | A value is one of a few shapes, like the payment | 3.10; assert_never 3.11 |
| Typestate classes | The order of operations | Ordinary objects, and every transition allocates one | Steps must happen in sequence, like the invoice | 3.5, with the first annotations |
pydantic BaseModel | The shape, like a dataclass | Model construction performs the configured validation | The border, where data arrives as text | a library |
TypeScript
| Construct | The checker holds | At run time, and what it costs | Reach for it when | Since |
|---|---|---|---|---|
type alias | Nothing; the same type under a new name | Erased. The compiler emits nothing at all | A long signature needs a short, honest name | 1.4 |
Brand (unique symbol) | The label, like NewType | Erased, and the cast costs nothing; the plain value remains | Two same-shaped values must never swap | 2.7 |
| Literal union | A closed set of values | Erased | A field or flag has a fixed menu | 1.8 |
enum | A closed set with named members | The compiler emits a real object, and a member is a property read | Rarely: plain enums break under type-stripping runtimes, and a const object with a derived union covers the need | 1.0 |
Object type, interface | The shape: property names and types | Erased | Data with named fields, which is most data | 1.0 |
class | The shape and the methods | A real object; instanceof works, and construction costs about what an object literal does | Identity or behaviour matters, as in the retry errors | 1.0 |
Discriminated union + never | Exhaustiveness: every reader handles every state | Erased, though the tag is a real property in every object | A value is one of a few shapes, like the payment | 2.0 |
| Typestate object types | The order of operations | Erased, and every transition allocates one object | Steps must happen in sequence, like the invoice | 2.0 |
satisfies + as const | Conformance to a type without widening the literal | Erased | A value must match a shape and keep its exact keys | 4.9; as const 3.4 |
| zod schema | The inferred static type | Schema validation executes; JSON decoding is a separate operation | The border, where data arrives as text | a library |
These tables describe runtime operations, not measured overhead. This page has no retained benchmark supporting nanosecond costs or cross-language speed comparisons. TypeScript removes type-only declarations from generated JavaScript. Python type objects, constructors, validation and data allocation can still do runtime work. Measure the same operation, inputs, versions and build settings against an explicit baseline before claiming a speed difference. The measurement guide explains that comparison.
Count the other costs too:
- Data from the wild arrives dirty, and a model that holds only clean values can't load the record you need to repair.
- A parser that stops at the first bad field can't collect every mistake at once.
- Types named
ValidThisandCheckedThatmultiply. - Every invariant you add is a promise your fixtures must keep before they can build anything at all.
Where this goes next
The final cell combines the changes from this lesson. Try the five starting mistakes again and press Type check. Then run the behavior checks; passing the type checker cannot establish every application rule.
The payments example applies related ideas: Making it unrepresentable. The examples behind this page live in tests/typesafety, and tests/typesafety.rs keeps them honest.
Turn your bugs into type errors.
Make illegal states unrepresentable.
Parse, don't validate.
How does this page work?
Edit any cell on this page and press a button. Run and lint execute in this browser tab; Python type checking opens Astral's official ty playground.
Run, Python. Pyodide is CPython compiled to WebAssembly. The first click loads it from a CDN. Each run hands your cell to the interpreter with fresh globals and shows what it printed.
Type check, Python. The button copies your edited cell and opens Astral's official ty playground; paste it into main.py to see the diagnostics. The GitHub test suite checks the same files with ty==0.0.80 and Python 3.14. The captured checker words below come from that pinned CLI. Astral does not publish a browser package for embedding ty here, so the hosted playground may advance before this repository updates its pin.
TypeScript. tsc was always JavaScript, so one CDN script is the whole compiler. Diagnostics use the same strict flags as the repository's tests; Run transpiles and evaluates.
Lint. Ruff is Rust, compiled to WebAssembly. It is Ruff itself.
To edit this page. The prose is docs/type-safety.html. The code cells are files under tests/typesafety/, one Python and one TypeScript per example; each cell's Edit in GitHub button opens its own pair. Change one, then use a dedicated runner to run UPDATE_SITE_DATA=1 cargo test --test typesafety to re-check it and regenerate the page's data. The buttons live in docs/type-safety.js.