14.2 Types you write down
- Approved by
- Panaversity ·
In everyday life. A paper form has boxes for the date, with "MM/DD/YYYY" printed under them, and checkboxes for delivery: ground, two-day, overnight. Paper cannot stop anyone writing "whenever", so a clerk checks each answer once, when the form arrives.
What you will learn. How to write down which values your data may hold, and where text from outside becomes one of them.
Why it matters. Once those values are written down, the type checker checks every later change against them, the agent's included.
What more can a type say?
Exactly which values are allowed. In Chapter 13, a type label said what kind of value a variable held. Here you decide the shape of your own data, and the agent writes it down.
Start with the form itself. A record type is the blank form: it names each box, called a field, and says what kind of answer goes in it. Here is Brightline's invoice form with four of its seven boxes, and then one invoice filled in. Predict what it prints.
// the blank form: each box, and
// the kind of answer it takes
type Invoice = {
number: string;
vendorId: string;
// a date as text, or nothing
dueDate: string | null;
amountCents: number;
};
// one form, filled in
const inv: Invoice = {
number: "INV-8305",
vendorId: "V005",
dueDate: null,
amountCents: 735000,
};
console.log(inv.number, inv.dueDate);INV-8305 null| Language | How the form is written |
|---|---|
| TypeScript | type Invoice = { ... } names the type. Each line inside is a field and its type. string | null means text, or nothing. |
| Python | @dataclass turns a class that only lists fields into a record type, and frozen=True means a record cannot be changed once it is made. str | None means text, or nothing. 14.3 explains classes. |
A type that says "this, or that", as the due date's does, is a union.
How does a type allow only a few exact values?
With a literal type. It is the form's row of checkboxes: only these answers exist. Here is a small one, with two of Brightline's five terms, a dictionary of the days each one gives, as in 13.7, and a function that takes only Terms. Predict which call the type checker refuses.
// the checkboxes: Terms is one
// of these two values.
// | means "or"
type Terms = "Net 15" | "Net 30";
// the days each one gives
const DAYS: Record<Terms, number> = { "Net 15": 15, "Net 30": 30 };
// terms must be one of them
function days(terms: Terms): number {
return DAYS[terms];
}
console.log(days("Net 30"));
console.log(days("Net 10"));14-2/try.ts(10,18): error TS2345: Argument of type '"Net 10"' is not assignable to parameter of type 'Terms'.The checker names the file, then the line and column of the call it refuses, counted in the file in 14-2, which has no comments.
Where does text from a file become a type?
Where it enters the program. Text read from a file is only a string. A literal type will not accept it, because it might be "Net 10". The type checker reads your code before the program runs, and never sees what arrives in a file.
So the program needs a type guard, such as Brightline's isTerms: code that runs with the program and reads the text that came in. It is the form's clerk: it answers true or false, once, where the text enters. The checker believes a true answer, and treats the text as Terms.
A cast, such as as Terms, skips the clerk: it tells the checker to believe the text without looking.
Brightline's full Terms has all five values, so its clerk checks all five. Predict both answers.
// the clerk: is this text
// one of the Terms?
// "text is Terms": the checker
// believes a true answer
function isTerms(text: string): text is Terms {
// is the text on the list?
// includes answers that
return ["Due on receipt", "Net 15", "Net 30", "Net 45", "Net 60"].includes(text);
}
console.log(isTerms("Net 30"), isTerms("Net 10"));true falseAt work. Ana has the agent change one line: the terms parameter of dueDate goes from string to Terms. The type checker reports six errors. Four pass raw text from a file straight into the calculation. One is the test that checks unknown terms on purpose. One is a call an agent wrote with "Net 10", terms Brightline has never used. Ana decides two things, and the agent makes both changes: check the text once, where it is read, and have that one test expect the error.
What does a type do while the program runs?
Nothing, by itself. Neither language checks its type labels while the program runs. A type protects you only when the type checker runs, which is why it runs on every change. Checking data while the program runs is the job of 14.4.
Try it
The file in 14-2 is the two-term block above, without its comments. Run it and investigate, as in 13.1.
Run the checker. Send: "Run the file, then check it with the type checker. Show me what each prints." The file runs, and the checker refuses one line.
Modify. Send: "Write the second call with a cast, so the checker believes it: as Terms in TypeScript, or cast(Terms, ...) in Python. Don't run anything yet." Will the checker accept it now? What will the file print? Then ask the agent to run the checker and the file.
Make. Send: "Add a function that takes text, answers whether it is one of the allowed terms, and reports it if not. Use it for "Net 10" instead of the cast."
What you should see. The checker accepts the cast, and the run is still wrong: undefined in TypeScript, a KeyError in Python.
The operating rule: write the allowed values into the types, check raw text once where it enters the program, and let the type checker check every line after that.

Figure 14.2. The clerk's check, in code. Text from outside is checked once as it comes in.
Next. A type describes one value. 14.3 holds several values together, with the functions that work on them.
Check yourself
Question 1 / 6
0 answered
The type checker passes this agent code, but it prints INV-5317 undefined.type Terms = "Due on receipt" | "Net 15" | "Net 30" | "Net 45" | "Net 60"
const DAYS: Record<Terms, number> = { "Due on receipt": 0, "Net 15": 15, "Net 30": 30, "Net 45": 45, "Net 60": 60 }
const row = { invoice: "INV-5317", terms: "Net 90" }
const terms = row.terms as Terms
console.log(row.invoice, DAYS[terms])What is the bug?
Sources
- Owner
- Panaversity