Sub topic 5
How `satisfies` Guides Inference
This chapter assumes you know basic TypeScript types, union types, object literals, tuples, and Record. It also assumes you know that TypeScript can infer a type from a value or use a type annotation that you provide.
The satisfies operator checks an expression against a type. It also gives the expression a contextual type, which guides how TypeScript infers parts of that expression. Unlike an annotation, satisfies does not replace the expression's resulting type.
Contextual typing
Contextual typing means that TypeScript uses the expected type around an expression to infer missing details.
For example, the type of handler tells TypeScript that the parameter is a string:
const handler: (message: string) => number = (message) => {
return message.length;
};
console.log(handler("ready"));The parameter message has no annotation. TypeScript gets its type from the function type on the left.
The same idea works with satisfies:
type Handlers = {
onMessage: (message: string) => number;
};
const handlers = {
onMessage: (message) => message.length,
} satisfies Handlers;
console.log(handlers.onMessage("ready"));The expected type from satisfies Handlers gives message the type string. TypeScript checks that onMessage is a compatible function, while handlers.onMessage remains a function with its inferred parameter and return types.
A useful model is:
Context for nested values
Contextual typing also helps with nested object properties and arrays. Consider a configuration type:
type CommandConfig = {
run: (input: string) => string;
aliases: string[];
};
const command = {
run: (input) => input.trim().toUpperCase(),
aliases: ["go", "start"],
} satisfies CommandConfig;
console.log(command.run(" build "));
console.log(command.aliases[0]);Here, input is inferred as string because run is expected to have the type (input: string) => string. The aliases array is checked as an array of strings.
The check applies recursively. If a nested property has the wrong type, TypeScript reports the problem where it appears:
type Settings = {
server: {
port: number;
host: string;
};
};
const settings = {
server: {
port: 8080,
host: "localhost",
},
} satisfies Settings;
console.log(settings.server.port);The expression keeps its object structure, so settings.server.port is known as a number. The target type supplies requirements, but it does not turn the whole value into a variable whose type is exactly Settings.
Literal values and unions
A contextual type can guide inference toward a permitted union member. This is useful for configuration values:
type LogLevel = "debug" | "info" | "error";
type LoggerConfig = {
level: LogLevel;
enabled: boolean;
};
const logger = {
level: "info",
enabled: true,
} satisfies LoggerConfig;
console.log(logger.level);The value "info" is checked against LogLevel. The property also retains useful information about the value that was written. If you need all literal values to remain exact for later type computation, combine satisfies with as const.
const levels = {
development: "debug",
production: "error",
} as const satisfies Record<string, LogLevel>;
type Environment = keyof typeof levels;
type ConfiguredLevel = (typeof levels)[Environment];
console.log(levels.production);Environment is "development" | "production", and ConfiguredLevel is "debug" | "error".
Tuples and arrays
A target type can also guide an array literal toward a tuple shape. A tuple is an array type with a fixed number of positions and known types.
type RGB = [number, number, number];
const red = [255, 0, 0] satisfies RGB;
console.log(red[0] + red[1] + red[2]);The array must have exactly three numeric elements. This is different from checking only number[], which allows any length.
You can use this with a keyed color map:
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());
console.log(palette.red.map((channel) => channel * 2));The union string | RGB gives each property an allowed shape. TypeScript checks the values against that union while preserving the useful types of the individual properties. Therefore, palette.green can be used as a string and palette.red can be used as an RGB tuple.
The role of `as const`
as const changes mutability and literal inference. Arrays become readonly tuples, and object properties become readonly literal properties.
const names = ["Ada", "Linus"] as const satisfies readonly string[];
console.log(names[0]);The target type must allow readonly data. A readonly tuple cannot be assigned to a mutable string[], because mutable code could try to change it.
For objects, the combination is useful when you want a precise set of keys and values:
const routes = {
home: "/",
user: "/users/:id",
} as const satisfies Record<string, `/${string}`>;
type Route = (typeof routes)[keyof typeof routes];
const selectedRoute: Route = routes.user;
console.log(selectedRoute);The template literal type ` /${string} requires every route to start with /. as const preserves the exact route strings, and satisfies` validates the rule.
Common inference mistakes
- Use a contextual type when a callback parameter would otherwise have an implicit
anytype. - Use a tuple target when array length and position matter.
- Use
readonlyin the target when combining it withas const. - Do not assume that
satisfiesconverts the value into the target type. It only checks compatibility. - Do not use
satisfiesas a substitute for parsing or validating external data.
Exercise
Why does satisfies help TypeScript infer the parameter type in { run: (input) => input.length } satisfies { run: (input: string) => number }?
Show answer
The target type provides contextual typing. It tells TypeScript that run receives a string, so input.length is checked as a string operation.