Sub topic 2
The problem: annotations throw away precision
This chapter assumes you know basic TypeScript types, union and literal types, tuples, and Record. You should also be comfortable with the idea that TypeScript infers a type when you don't write one. Here you will see a problem that comes up in everyday code. You write a type annotation to make sure an object has the right shape. The annotation checks the shape, but it also erases what TypeScript knew about each value. The next chapters build on this problem, so it is worth understanding in detail.
Two ways a variable gets its type
A variable's type comes from one of two places. TypeScript infers it from the initializer, or you declare it with an annotation.
const name = "Ada"; // type "Ada" (a literal type, because const cannot change)
let title = "Dr"; // type string (let can change, so the literal widens)
const user = { name: "Ada", age: 36 }; // { name: string; age: number }
user.age = 37; // allowed: properties of an object literal are mutableInference is precise about what it sees. If you write "Ada", it knows you have a string, and it knows the exact shape of the object. But inference does not check that shape against anything you intend. If you misspell a property, inference happily records the misspelled name.
An annotation does the opposite. It states the type you want and makes TypeScript verify the initializer against it:
type Options = { port: number; host?: string };
const options: Options = { port: 80, host: "localhost" };If the object does not fit Options, you get an error at the declaration. That is the benefit of annotations. The cost is what this chapter is about.
The rule: the declared type replaces the inferred type
When you annotate a variable, the variable gets the annotated type. TypeScript checks that the initializer is assignable to that type. After that check it discards what it learned from the initializer. Everything downstream sees only the declared type.
Usually this is what you want. For a variable holding a User, you want code to treat it as a User. It becomes a problem when the declared type is deliberately broad, such as a union, and each value in your object is a more specific member of that union.
A worked example: a palette of colors
Suppose you store colors. A color may be a hex string or an RGB tuple of three numbers. Each color name must have an entry.
type Color = "red" | "green" | "blue";
type RGB = [number, number, number];
const annotated: Record<Color, string | RGB> = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255],
};The annotation does useful work here. It rejects a missing key, an unknown key, and a value that is neither a string nor a tuple of three numbers. It also gives the array literals a contextual type, so [255, 0, 0] is read as an RGB tuple and not as number[].
Now try to use the values:
type Color = "red" | "green" | "blue";
type RGB = [number, number, number];
const annotated: Record<Color, string | RGB> = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255],
};
// @ts-expect-error 'toUpperCase' does not exist on type 'string | RGB'.
annotated.green.toUpperCase();
// @ts-expect-error 'map' does not exist on type 'string | RGB'.
annotated.red.map((n) => n * 2);You wrote "#00ff00" on the line above and [255, 0, 0] on the line before that. The compiler no longer remembers either. Every property now has the type string | RGB, because that is the declared type of the Record's values.
What you can still do with a union
With a union type, TypeScript allows only operations that are valid for every member. string and the RGB tuple happen to share a few members, and one of them is a trap:
type Color = "red" | "green" | "blue";
type RGB = [number, number, number];
const annotated: Record<Color, string | RGB> = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255],
};
const n = annotated.green.length; // compiles, type number
console.log(n); // 7, but for annotated.red it would be 3The code compiles because both string and a three-element tuple have a length property of type number. The type system cannot tell you which one you have, so a bug that depends on the difference would pass type checking.
Why assignment narrowing does not rescue you
You may know that TypeScript narrows a variable when you assign to it:
const id: string | number = "abc-123";
console.log(id.toUpperCase()); // works: id is narrowed to string by the assignmentThis works because the variable id itself has a union type, and the assignment tells TypeScript which member it holds. It does not extend to properties inside an object. In the palette, the variable annotated has the object type Record<Color, string | RGB>. That type is not a union. Its properties are unions, and TypeScript does not narrow a property because of what the initializer contained.
const config: { port: number | string } = { port: 8080 };
// @ts-expect-error 'toFixed' does not exist on type 'string | number'.
config.port.toFixed(0);So you cannot rely on narrowing to recover the lost precision.
The usual workaround: narrow at every use
The standard answer is to check the type at runtime wherever you need the specific one:
type Color = "red" | "green" | "blue";
type RGB = [number, number, number];
const annotated: Record<Color, string | RGB> = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255],
};
const green = annotated.green;
if (typeof green === "string") {
console.log(green.toUpperCase());
}
const red = annotated.red;
if (Array.isArray(red)) {
console.log(red.map((n) => n * 2));
}This works, but it has two costs. First, it adds runtime code only to satisfy the compiler about something you already know. Second, the branch you skip is silent. If someone changes green to a tuple, the if simply stops running, and nothing tells you the code is now dead.
The same problem with literal types
Unions of object types are not the only case. Annotations also widen literal types, because the declared type is the only thing that survives.
type Theme = "light" | "dark";
function applyTheme(theme: Theme): void {
console.log(`Using the ${theme} theme`);
}
const settings: { theme: string } = { theme: "dark" };
// @ts-expect-error Argument of type 'string' is not assignable to parameter of type 'Theme'.
applyTheme(settings.theme);The value "dark" is a valid Theme, and you wrote it yourself. But the annotation said string, so string is all that remains. If you change the annotation to { theme: Theme }, the call works, and settings.theme has the type Theme. Even then the type is the whole union and not "dark". Any code that depends on the exact value, such as picking a branch or indexing a lookup table, cannot see it.
Broad annotations hide typos
An annotation with a very general key type can make you lose protection instead of gaining it. Record<string, string> is a common choice for a lookup table:
const routes: Record<string, string> = {
home: "/",
user: "/users/:id",
};
const href = routes.hom; // no error: any string key is allowed
console.log(href); // undefined at runtime, but typed as stringThe annotation says any string key is valid and every value is a string. TypeScript no longer remembers that the only keys are home and user. The misspelled hom compiles, and the result is typed string even though it is undefined at runtime.
If you enable the compiler option noUncheckedIndexedAccess, the result type becomes string | undefined. That forces a check, but it still does not tell you that hom is not a real key. The information about the real keys is gone.
The opposite approach: skip the annotation
If annotations lose precision, you might drop them. Inference keeps precise types, but then nothing checks the shape against your intent. For the palette it fails in a different way:
type Color = "red" | "green" | "blue";
type RGB = [number, number, number];
function paint(palette: Record<Color, string | RGB>): void {
console.log(Object.keys(palette));
}
const inferred = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255],
};
// @ts-expect-error 'number[]' is not assignable to 'string | RGB'.
paint(inferred);Without an annotation, nothing tells TypeScript that [255, 0, 0] should be a tuple, so it infers number[]. The object is then rejected, but only at the call to paint, which may be in another file. A mistyped key such as bleu would also be reported at the use site and not at the definition. Inference alone gives you no check where you declare the value.
Summary of the trade-off
The table compares what each approach gives you for the palette.
| Approach | Checks the object against `Record<Color, string \ | RGB>` at the declaration | Keeps `green` as `string` and `red` as a tuple |
|---|---|---|---|
| Inference only (no annotation) | No | Partly: `red` is inferred as `number[]`, not as a tuple | |
| Annotation | Yes | No: every property is `string \ | RGB` |
You want both columns to be "yes". You want TypeScript to check the object when you declare it, and you want it to keep the specific type of each property afterward. An annotation cannot do both, because it has one job: to set the type of the variable. Checking the initializer is only a side effect of that job.
Annotation versus assertion
Another tempting shortcut is a type assertion with as. It can make the error go away, but it works by turning off checks, not by recovering precision. The next chapter covers why that fails. For now, keep in mind that the problem is the gap between two operations. Checking a value against a type and giving a value a type are separate steps. An annotation does both at once, and you cannot take only the checking.
What to look for in your own code
These patterns signal the problem described here:
- A configuration object annotated with an interface whose properties are unions, followed by
typeofchecks or casts where the object is used. - A lookup table annotated as
Record<string, X>where the keys are really a fixed, known set. - A literal such as
"dark"or443stored in a property annotated with a general type likestringornumber, which is later passed to a function that needs the specific literal. - An object left without an annotation to keep precision, then rejected far away from where it was written.
The next chapter looks at the most common attempt to avoid the annotation, the as assertion, and shows why it is risky. After that, satisfies addresses the gap directly, checking the value without changing its type.
Exercise
Given const cfg: { retries: number | "unlimited" } = { retries: 3 };, why does cfg.retries.toFixed(0) fail to compile, and why does narrowing on assignment not help?
Show answer
The annotation makes cfg.retries have the type number | "unlimited", and toFixed does not exist on the string member, so the call is rejected. Assignment narrowing applies only to a variable whose own declared type is a union. Here the variable cfg has an object type, and the union is on one of its properties, which the initializer does not narrow.
Exercise
A team declares const flags: Record<string, boolean> = { darkMode: true, beta: false }; and later reads flags.darkmode. Does this compile, what is the type of the result, and what is the value at runtime?
Show answer
It compiles, because Record<string, boolean> allows any string key. The result is typed boolean (or boolean | undefined with noUncheckedIndexedAccess), but at runtime the value is undefined because the real key is darkMode. The annotation discarded the knowledge of which keys exist.
Exercise
Why does leaving the annotation off the palette object not solve the problem when the object is later passed to paint(palette: Record<Color, string | RGB>)?
Show answer
Without an annotation, nothing gives [255, 0, 0] a tuple type, so TypeScript infers number[], which is not assignable to RGB. The error appears at the call to paint, far from the object's definition, and a misspelled key would also only be reported there. Inference keeps precision but does not check the object where it is written.