Sub topic 2
The Problem: Annotations Throw Away Precision
Prerequisites
This chapter assumes that you know basic TypeScript types, union types, object literals, tuples, arrays, and type inference. You should also know that a type annotation tells TypeScript what type a variable must have.
TypeScript can often infer a more precise type from a value than the type you write in an annotation. A broad annotation can replace that precise information with a wider type. The value still works at runtime, but the compiler can no longer help you use its exact shape.
Inference keeps details
Consider this object:
const palette = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255],
};
console.log(palette.green.toUpperCase());
console.log(palette.red.map((component) => component * 2));TypeScript examines each property separately. It knows that:
palette.greenis a string.palette.redis an array of numbers.palette.blueis an array of numbers.
The inferred type is roughly:
{
red: number[];
green: string;
blue: number[];
}That type is more precise than one type that describes every property at once. The compiler can allow string methods on green because it knows the property contains a string.
A type annotation can change this result:
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 says that every property has the type string | RGB. It does not say that green is specifically a string or that red is specifically an RGB tuple.
// Error: Property 'toUpperCase' does not exist on type 'string | RGB'.
annotated.green.toUpperCase();The error is correct from the annotated variable's point of view. If annotated.green could be either a string or a tuple, calling toUpperCase would be unsafe.
What widening means
Widening means replacing a specific type with a broader type.
For example, the literal value "green" can have the literal type "green", which means exactly that one string. A broader type, string, means any string:
const exactColor: "green" = "green";
const broadColor: string = "green";The second variable contains the same runtime value, but its type carries less information.
The same idea applies to objects. A precise object type can distinguish the properties:
type PrecisePalette = {
red: [number, number, number];
green: string;
blue: [number, number, number];
};A broad object type groups them together:
type BroadPalette = Record<Color, string | RGB>;Both types describe a valid palette. PrecisePalette gives the compiler more information about each property. BroadPalette is useful when you want to treat every value uniformly, but it cannot preserve which kind of value belongs to each key.
| Declaration | Type known for `green` | Information preserved | Column | Column |
|---|---|---|---|---|
| Inferred object | `string` | Each property has its own type | ||
| `Record<Color, string \ | RGB>` annotation | `string \ | RGB` | Only the shared value type |
| `as const` object | `"#00ff00"` | Exact values and readonly status |
Why annotations are still useful
A type annotation is not a mistake. It is useful when you want to declare the public type of a value or deliberately limit what code may rely on.
For example, a function can accept any palette whose values are strings or RGB tuples:
type Color = "red" | "green" | "blue";
type RGB = [number, number, number];
function printPalette(palette: Record<Color, string | RGB>): void {
for (const color of Object.keys(palette) as Color[]) {
console.log(color, palette[color]);
}
}
const palette: Record<Color, string | RGB> = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255],
};
printPalette(palette);Inside printPalette, the function must handle both possible value types. That is the correct trade-off for a function designed to accept both forms.
The problem appears when you need both benefits at once:
- Validate that the object follows a required structure.
- Keep the specific type of every property for later code.
A normal annotation provides validation, but the variable is viewed through the annotation's type. In the palette example, the compiler forgets that green is a string.
The loss happens at the variable boundary
The value itself has not changed. The annotation changes the type assigned to the variable:
flowchart TD
A["Object literal"] --> B["red is RGB"]
A --> C["green is string"]
A --> D["blue is RGB"]
B --> E["Record<Color, string | RGB> annotation"]
C --> E
D --> E
E --> F["Each property is viewed as string | RGB"]This distinction matters when reading compiler errors. TypeScript is not saying that the runtime value suddenly became a tuple or that the string method will definitely fail. It is saying that the type information available at that variable is too broad to prove the method is safe.
You can narrow the value before using it:
function formatValue(value: string | RGB): string {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.join(", ");
}
console.log(formatValue(palette.green));
console.log(formatValue(palette.red));Narrowing solves the immediate error, but it adds work that would not be needed if the property-specific type had been preserved.
Why `as` does not restore the information
A type assertion uses as to tell TypeScript to treat an expression as another type:
const asserted = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255],
} as Record<Color, string | RGB>;This does not preserve the property-specific types. asserted.green is still viewed as string | RGB.
Assertions can also hide errors because they tell the compiler to trust you:
type Options = {
port: number;
host?: string;
};
const options = {
port: 80,
hots: "localhost",
} as Options;
console.log(options.port);The misspelled hots property is accepted by the assertion, even though the intended property was probably host. An annotation would report that excess property on the object literal. The difference is important: annotations check compatibility, while assertions primarily override the compiler's view.
The satisfies operator addresses this particular tension. It checks an expression against a type without replacing the expression's inferred type. The next chapter examines its syntax and behavior.
Exercise
Why does annotated.green.toUpperCase() fail when annotated is declared as Record<Color, string | RGB>, even though the assigned value for green is a string?
Show answer
The annotation makes annotated.green visible as string | RGB. TypeScript must account for the tuple possibility before allowing a string-only method.