DEV Community

Cover image for satisfies, as, as const, and is: How TypeScript Labels a Value
Mohsen Fallahnejad
Mohsen Fallahnejad

Posted on Edited on Originally published at bitlyst.blog

satisfies, as, as const, and is: How TypeScript Labels a Value

type Config = { mode: "dark" | "light"; home: `/${string}` };

const config: Config = { mode: "dark", home: "/" };

config.mode; // "dark" | "light" — the exact "dark" is gone
config.home; // `/${string}` — the exact "/" is gone
Enter fullscreen mode Exit fullscreen mode

You wrote "dark" and "/". The annotation stored the whole allowed set. A function that only accepts "dark" now rejects config.mode.

The mental model: a name tag

TypeScript likes a general label. as const laminates the exact letters. satisfies checks your value against a type, then hands the original tag back. as writes a new tag, and the new tag can be a lie. is hands over a new tag only when a function returns true.

A bare const string is already exact: const home = "/" has the type "/". Objects are where the letters disappear. With no annotation, { mode: "dark" } is { mode: string }.

AI-generated illustration. The lock keeps the exact letters, the stamp checks them, and the blank sticker is a label you wrote yourself.

as const laminates the exact value

const routes = {
  home: "/",
  about: "/about",
} as const;

routes.home; // "/"
routes.home = "/nope"; // error: readonly
Enter fullscreen mode Exit fullscreen mode

The type is { readonly home: "/"; readonly about: "/about" }. (typeof routes)[keyof typeof routes] is then "/" | "/about", the usual stand-in for an enum. A list works the same way: ["red", "green"] as const is readonly ["red", "green"]. That pattern is the one in TypeScript enums vs alternatives.

A type annotation replaces the label

const config: Config = { mode: "dark", home: "/" };
config.mode; // "dark" | "light"
Enter fullscreen mode Exit fullscreen mode

The : Config checks the object. A missing key is an error, and so is mode: "nope". After the check, the variable's type is Config. "dark" has been replaced by "dark" | "light", and "/" by "a string that starts with /".

satisfies checks, then hands the label back

const config = { mode: "dark", home: "/" } satisfies Config;

config.mode; // "dark"
config.home; // "/"
Enter fullscreen mode Exit fullscreen mode

Config is the guest list. "dark" has to be one of the modes, home has to start with /, and an extra key is an error. Then the original letters stay. config.mode is "dark", so it passes a function that only accepts "dark".

Assigning "light" later is an error: the property's type is the literal "dark", even though Config allows both. If the property in Config is a plain string, satisfies widens it to string too. The exact letters survive when that type is a union of literals, a template literal type like `/${string}`, or when you laminate first:

const config = { mode: "dark", home: "/" } as const satisfies Config;
Enter fullscreen mode Exit fullscreen mode

as const runs first, then satisfies checks the frozen value. The result is readonly, and it still has to match Config.

as writes a new label

const mode = "nope" as "dark" | "light"; // no error
mode; // "dark" | "light"
Enter fullscreen mode Exit fullscreen mode

Both sides are strings, so the checker steps aside. The type says "dark" | "light". The value at runtime is still "nope". Nothing throws.

Use as where a value enters typed code from outside it: JSON.parse(text) as Config, or a DOM node you already proved is there. The proof is yours. The checker will not repeat it.

is narrows when a check returns true

function isDark(value: unknown): value is "dark" {
  return value === "dark";
}

if (isDark(input)) {
  input; // "dark"
}
Enter fullscreen mode Exit fullscreen mode

value is "dark" is a type predicate. In the true branch, input wears that label. The same annotation on a filter callback is why the result becomes "dark"[] instead of unknown[]:

const darks = items.filter((item): item is "dark" => item === "dark");
Enter fullscreen mode Exit fullscreen mode

The checker trusts the predicate. A function that return trues still compiles, and the true branch still narrows. The === is the part that protects you.

In practice

Use as const on route maps, option lists, and config you want as a union. Use satisfies when an object must match a shape and you still want the specific values. Use as const satisfies when you want both the shape check and the readonly literals.

Save as for a boundary you have already proved. For unknown, write an is function whose body does the check, and narrow with that.

Honest stakes: as, as const, and satisfies are erased when TypeScript becomes JavaScript. They cannot catch a bad value at runtime. A wrong as compiles and fails later, on a property that is not there. The is in a predicate is erased too, and the function body still runs, so the check is real if you wrote one. You will type as const most weeks. satisfies shows up on config objects. A file full of as usually means a missing predicate.

Say it in an interview

"as const keeps the exact literal and makes it readonly. An annotation checks a value and then the variable's type becomes that annotation, while satisfies checks and keeps the specific type. as replaces the type without a check when the two types overlap, so it can be wrong, and it disappears at runtime. is is a function return type: when the function returns true the argument narrows, and the function body is what still runs."

Cheat sheet

What the variable's type becomes Catches a bad value? At runtime
as const The exact literals, marked readonly No. It only freezes what you wrote Erased
: Config Config Yes Erased
satisfies Config The exact value, which must be a Config Yes Erased
as Config Config Only when the two types do not overlap Erased
value is Config The argument becomes Config when the function returns true Only the check in the function body The function runs. The is type is erased

TL;DR

  • Objects and arrays widen. { mode: "dark" } is { mode: string }. A bare const string stays "dark".
  • as const keeps the exact literals and marks them readonly.
  • An annotation checks the value, then the variable's type becomes the annotation.
  • satisfies checks the value and leaves the exact type in place.
  • as overwrites the type. "nope" as "dark" compiles, and the value is still "nope".
  • value is "dark" narrows the argument in the true branch. The function body is the runtime check.

Going deeper

Advanced and optional. Everything above is enough to explain this in an interview. This part is for the curious: full numbers, edge cases and what's still unproven.

The false branch

On a union, a false predicate drops the matched member. If mode is "dark" | "light" and isDark(mode) returns false, mode is "light". On unknown, the false branch stays unknown. There is nothing left to subtract.

When the union has two different shapes

satisfies earns its place when one property may be two kinds of value, and you still want the kind you actually wrote:

type RGB = [number, number, number];
type Palette = Record<"red" | "green" | "blue", string | RGB>;

const palette: Palette = {
  red: [255, 0, 0],
  green: "#00ff00",
  blue: [0, 0, 255],
};

palette.green.toUpperCase(); // error: green might be an RGB triple
Enter fullscreen mode Exit fullscreen mode

With satisfies Palette, green stays a string and red stays a triple of three numbers. toUpperCase() compiles. A typo in a key still fails.

! is the same kind of claim as as

const input = document.querySelector("input");
input.value; // error: input might be null
input!.value; // you said it is not
Enter fullscreen mode Exit fullscreen mode

The postfix ! drops null and undefined from the type. It does not look at the DOM. If the element is missing, that line throws when it runs.

as unknown as forces a lie the checker rejected

A direct assertion has to be plausible. { mode: "nope", home: "/" } as Config fails, because "nope" and "dark" | "light" do not overlap. Two steps get around that:

const config = { mode: "nope", home: "/" } as unknown as Config; // compiles
Enter fullscreen mode Exit fullscreen mode

unknown overlaps with everything, so the second as is unchecked. Treat that pair as a sign the types are fighting the value.

const type parameters are as const for arguments

TypeScript 5.0 lets a function ask for the narrow type, so callers do not write as const themselves:

function routeOf<const T extends string>(path: T) {
  return path;
}

routeOf("/"); // type is "/"
Enter fullscreen mode Exit fullscreen mode

<const T extends readonly string[]>(values: T) does the same for a list: ["red", "green"] is inferred as readonly ["red", "green"].

Further reading


Originally published on Bitlyst.

Top comments (0)