TypeScript 4.9 retrospective: Check a configuration contract with satisfies
Use the satisfies operator introduced in TypeScript 4.9 to check a finite route configuration, retain literal types, and separate static checking from runtime validation.
Archive retrospective · Topic year 2022
In this article
The configuration problem TypeScript 4.9 addressed
The TypeScript 4.9 release notes introduced satisfies as a way to check whether an expression is compatible with a type while retaining more specific information about its inferred type. Consider a small web application with a fixed list of read routes. Each route has a cache lifetime and a set of read methods. Another part of the application wants to use a literal value defined by the configuration. As the configuration changes, a missing route, misspelled name, or unsupported method should be detected at the point where the data is defined. The operator applies during TypeScript compilation. It adds no runtime validator to the JavaScript emitted for the expression. That distinction matters when the same application also accepts settings from files or network responses. This example uses a source-code object first, then identifies the checks that still belong at runtime. Keeping those responsibilities explicit helps teammates understand what a successful compilation actually verifies.
Define three routes against one contract
ReaderRoute names the three routes the application accepts. CachePolicy specifies a numeric lifetime and a readonly list containing only GET or HEAD. Record requires that each route in the union have a configuration of that shape. The final two assignments show that TypeScript still sees the concrete value on the story row. Assigning that number to a variable whose only permitted value is 60 would fail if the property had already been widened to number. The const assertion is a separate part of this pattern. It preserves literals and makes the array data readonly at the type level, so the policy uses a readonly array as its target. That prevents an accidental push through this typed reference during development. It does not freeze the emitted JavaScript object. Runtime ownership and mutability are separate aspects of how the application shares configuration between components.
type ReaderRoute = "archive" | "story" | "search";
type CachePolicy = {
ttlSeconds: number;
methods: readonly ("GET" | "HEAD")[];
};
const policy = {
archive: { ttlSeconds: 120, methods: ["GET", "HEAD"] },
story: { ttlSeconds: 60, methods: ["GET"] },
search: { ttlSeconds: 0, methods: ["GET"] },
} as const satisfies Record<ReaderRoute, CachePolicy>;
const storyTtl: 60 = policy.story.ttlSeconds;
const storyMethod: "GET" = policy.story.methods[0];
console.log(storyTtl, storyMethod); // 60 GET
Try the boundaries with controlled changes
Save the example as config.ts and compile it with strict type checking. Executing the JavaScript prints 60 GET. Temporarily remove search to see the missing key reported. Restore it and replace one method with POST to see how the policy constrains values inside each route. Add an extra literal key called seach to exercise excess property checking. Change only one property at a time so the meaning of each failure is clear. The configuration in this example is an object literal at the checking site. TypeScript uses structural compatibility, and its excess property checks are more specific than a universal exact-object type. An object first stored in another variable can have additional properties and still be compatible with the required fields. If exact keys matter to application behavior, keep the check near the definition and apply a dedicated boundary rule to external data.
Compare a type annotation and an assertion
An explicit annotation such as const broad: Record<ReaderRoute, CachePolicy> also catches missing required keys and incompatible values in a literal. Access through broad.story.ttlSeconds, however, exposes the property as number. That is a reasonable choice for a library boundary that only wants to advertise a general contract. Use the more specific type when internal code has a meaningful reason to rely on a known literal. A type assertion with as takes a different direction. It tells TypeScript how to treat an expression and can reduce the compiler’s ability to discover useful errors if employed as a shortcut. The assertion still has some compatibility checks, so it should not be described as blindly accepting every value. Nevertheless, it serves a different purpose from validating an authored configuration with satisfies. The route example makes that design choice visible at the line where the object is created.
Validate runtime JSON at its own boundary
Settings read from a file or endpoint are external runtime data. Treat the parsed value as unknown until the application has checked it. An operational cache lifetime might have to be a finite integer between zero and a documented upper limit. The type number does not encode that rule, so a negative lifetime satisfies the static shape in this example. Applying the real bounds at runtime makes a failure attributable to the specific route and field. Specify what to do with missing fields, unexpected fields and an empty method list. These may require different responses in a startup configuration and a user-facing import form. Diagnostics can report the affected route, the invalid field and the expected form without dumping the entire configuration. That is useful when another portion of the same file contains values that should not be logged.
Keep type checks and behavior tests together
When a new route enters the ReaderRoute union, the compiler points to the missing policy. A CI type check catches that error before release. A small runtime test can then make a real request and verify a response’s methods and cache headers. Setting a lifetime of zero in this example does not by itself prove that the application emits a no-store directive. The request handler must still translate values into observable behavior. To revisit the 2022 feature, use a TypeScript 4.9 or later compiler and repeat the controlled invalid edits. A newer compiler may phrase a diagnostic differently while identifying the same compatibility issue. For runtime configuration, retain examples of valid, missing and invalid values as behavior tests. Together these checks make the location and meaning of a configuration failure clear, without relying on the wording of one compiler version.
Reader discussion
Which bottleneck would you expect as this solution scales?
No comments yet. Be the first to contribute.
Write a comment