Sub topic 4
Meet satisfies: check without widening
This chapter introduces the satisfies operator. It assumes you know TypeScript's basic types, interfaces and type aliases, union and literal types, Record, and the difference between a type annotation and an inferred type. The previous chapters showed that annotations lose precision and that as assertions lose safety. This chapter shows how satisfies avoids both losses.
What satisfies does
satisfies was added in TypeScript 4.9. It has this form:
expression satisfies TypeIt does two things, in this order:
- It checks that the type of
expressionis assignable toType. If it is not, the compiler reports an error on the expression. - It gives the whole expression the type that TypeScript inferred for it. It does not give it
Type.
An annotation or an as assertion replaces the inferred type with the type you wrote. satisfies keeps the inferred type and uses Type only as a rule the value must follow.
Here is the palette example from the previous chapter, rewritten with satisfies:
type Color = "red" | "green" | "blue";
type RGB = [number, number, number];
const palette = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255],
} satisfies Record<Color, string | RGB>;
console.log(palette.green.toUpperCase()); // green is known to be a string
console.log(palette.red.map((n) => n * 2)); // red is known to be [number, number, number]With an annotation of Record<Color, string | RGB>, every property would have the type string | RGB. The calls to toUpperCase and map would then fail, because TypeScript would not know which member of the union each property holds. Here the object is still checked against the same Record type. Each property keeps its own type, so both calls compile.
The inferred type of palette is:
{
red: [number, number, number];
green: string;
blue: [number, number, number];
}You can confirm this by hovering over palette in your editor.
The three tools side by side
The diagram shows what each of the three tools does with the same object literal.
The same comparison as a table:
| Feature | Annotation `: T` | Assertion `as T` | `satisfies T` |
|---|---|---|---|
| Rejects values that do not match `T` | Yes | Only if the types do not overlap at all | Yes |
| Type of the variable afterwards | `T` | `T` | The inferred type of the value |
| Reports misspelled properties in object literals | Yes | No | Yes |
| Reports missing required properties | Yes | No, if the literal is a subtype of `T` or a supertype of it | Yes |
| Changes the emitted JavaScript | No | No | No |
The last row matters. All three constructs are erased when TypeScript compiles to JavaScript, so none of them has any runtime effect.
Reading the error messages
satisfies reports problems where the value is written. Here is a failing version of the palette. The misspelled key and the missing key are both reported:
type Color = "red" | "green" | "blue";
type RGB = [number, number, number];
// Error: Property 'blue' is missing, and 'bleu' is not a known property.
const broken = {
red: [255, 0, 0],
green: "#00ff00",
bleu: [0, 0, 255],
} satisfies Record<Color, string | RGB>;A wrong value type is also reported on the property itself. This snippet is commented out so the file still compiles:
type Color = "red" | "green" | "blue";
type RGB = [number, number, number];
const wrongValue = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0], // Error: Type '[number, number]' is not assignable to type 'string | RGB'.
};
// Uncomment the next line to see the error appear:
// const checked = wrongValue satisfies Record<Color, string | RGB>;Because the check is reported at the property, you can see which line is wrong without tracing a long assignability message.
Where you can use it
satisfies is an expression operator, not a declaration feature. An annotation can only appear on a declaration, such as a variable, parameter or return type. satisfies can appear anywhere an expression can. This includes return values, default exports, and arguments:
type Config = { port: number; host?: string };
export default {
port: 8080,
host: "localhost",
} satisfies Config;
function makeConfig() {
return { port: 3000, tags: ["dev", "local"] } satisfies { port: number; tags: string[] };
}
const config = makeConfig();
console.log(config.tags.length); // tags is string[]An export default expression cannot take an annotation, so satisfies is the only way to check it while keeping its type.
Precedence
satisfies has the same precedence as as. If you want to use a property of the checked value in the same expression, wrap it in parentheses:
const length = ("hello" satisfies string).length;
console.log(length); // 5Without the parentheses, "hello" satisfies string.length would be read as a type named string.length, which is a syntax error.
How the check works
You do not need the compiler's source code to use satisfies, but a working model helps you predict its behavior. For expr satisfies T, TypeScript does the following:
- It type-checks
exprusingTas the contextual type. This means that places inexprthat need a type from context, such as function parameters or array literals that could be tuples, take it fromT. - It checks that the resulting type is assignable to
T. Object literals are also subject to the excess property check, as the next chapter section covers. - It returns the type from step 1 as the type of the whole expression.
The contextual typing in step 1 explains why this compiles with no parameter annotation:
const handlers = {
click: (e) => e.x,
hover: (e) => e.x * 2,
} satisfies Record<string, (event: { x: number }) => number>;
console.log(handlers.click({ x: 10 })); // 10
console.log(handlers.hover({ x: 10 })); // 20The parameter e has no annotation of its own. TypeScript takes its type from the callback type in the Record. After the check, handlers.click and handlers.hover are still separate properties, each with the type (e: { x: number }) => number. The next chapter section covers contextual typing in more detail.
Literal types
Contextual typing can also stop a literal from being widened. Without a type to guide it, TypeScript widens the string "get" in a mutable property to string. If T says that property is a union of string literals, TypeScript keeps the literal:
type Method = "get" | "post";
const widened = { method: "get" };
// widened.method has type string
const checked = { method: "get" } satisfies { method: Method };
// checked.method has type "get"
const m: "get" = checked.method; // compiles
console.log(widened.method, m);The value is not narrowed beyond what you wrote. It is only protected from widening because T mentions literal types. If T has method: string, the inferred property would be string again.
Comparing the three on one example
Suppose a function accepts a Settings object and you want to keep exact property types for later use:
type Settings = {
retries: number;
endpoints: Record<string, string>;
};
const annotated: Settings = {
retries: 3,
endpoints: { primary: "https://a.example", backup: "https://b.example" },
};
// annotated.endpoints.primary is string (an index signature gives no key names)
// annotated.endpoints.typo is also allowed and has type string
const satisfied = {
retries: 3,
endpoints: { primary: "https://a.example", backup: "https://b.example" },
} satisfies Settings;
// satisfied.endpoints has exactly the keys primary and backup
// satisfied.endpoints.typo is an error
console.log(annotated.endpoints.primary);
console.log(satisfied.endpoints.backup);The annotation turns endpoints into a general string-to-string map, so a misspelled key later in your code compiles. With satisfies, endpoints is known to have exactly the keys primary and backup, so a misspelled key is an error at the use site. You still got the check against Settings.
What an assertion would have done
An as assertion also keeps the type you want, but it makes a different promise. It tells TypeScript to trust you:
type Options = { port: number; host?: string };
// Error: Object literal may only specify known properties, and 'hots' does not exist in type 'Options'.
// const checked = { port: 80, hots: "localhost" } satisfies Options;
// An assertion compiles without complaint, so the typo goes unnoticed.
const asserted = { port: 80, hots: "localhost" } as Options;
console.log(asserted.host); // undefined at runtime, although the code looked rightThe first declaration is commented out because it would be a compile error, and that error is the point. The assertion compiles and the typo goes unnoticed. Use as when you know something the compiler cannot. Use satisfies when you want the compiler to confirm what you have written.
When satisfies adds nothing
satisfies does not help in every situation. Three cases are worth knowing:
- The variable already has an annotation.
const x: T = value satisfies Tchecks twice and keeps the typeT. Pick one. - You want the variable to have the wider type on purpose. If later code assigns different members of a union to the variable, an annotation is correct. For example,
let status: "idle" | "busy" = "idle"must stay a union so that you can assign"busy"later. - The value is not a literal. If you write
someFunctionResult satisfies T, the check still works, but there is no literal for the operator to preserve. You only get the check.
let status: "idle" | "busy" = "idle"; // annotation is right: status must accept both values
status = "busy";
const initial = "idle" satisfies "idle" | "busy"; // fine, but adds little value
console.log(status, initial);Tooling and versions
satisfies needs TypeScript 4.9 or later. Other tools that read TypeScript syntax must also understand it, or they will fail with a parse error that mentions an unexpected token. If you see that error after adding satisfies, check the versions of your formatter, linter parser and Babel presets, as well as the compiler itself. Editors that bundle their own TypeScript version may also need updating.
The operator disappears when the code is compiled. This code:
const x = { a: 1 } satisfies { a: number };compiles to this JavaScript:
const x = { a: 1 };Since nothing remains at runtime, satisfies cannot validate data that arrives while the program runs, such as JSON from a network call. The last chapter in this tutorial covers that limit and the pitfalls around it.
Summary of the rules
expr satisfies Tfails to compile if the type ofexpris not assignable toT.- On success, the expression keeps its own inferred type. It does not take the type
T. Tsupplies contextual types, so callback parameters can go unannotated, and literals are not widened whenTasks for literal types.- Object literals get the excess property check, so typos are caught.
- It works on any expression and has the same precedence as
as. - It is erased at runtime and does no validation of its own.
Exercises
Exercise
A teammate writes const theme = { primary: "#fff", sizes: [1, 2, 3] } satisfies { primary: string; sizes: number[] };. What is the type of theme.sizes, and does theme.sizes.push(4) compile?
Show answer
The type of theme.sizes is number[], which is the type inferred from the array literal. push(4) compiles because the array is mutable. The satisfies clause only checked that the object fits the shape. It did not change the inferred type.
Exercise
What is the difference in outcome between const a = { port: 80, hots: "x" } as Options; and const b = { port: 80, hots: "x" } satisfies Options; when Options is { port: number; host?: string }?
Show answer
The as version compiles, so the misspelled hots is not noticed. The satisfies version is a compile error because the object literal specifies a property, hots, that does not exist in Options. Since satisfies applies the excess property check, it catches the typo.
Exercise
Why does this code give a syntax error, and how do you fix it? const n = "abc" satisfies string.length;
Show answer
satisfies expects a type after it, so string.length is read as a type name. To use the property of the expression, wrap the expression in parentheses: const n = ("abc" satisfies string).length;.