Skip to content

Instantly share code, notes, and snippets.

@martinrue
Created November 30, 2022 21:16
Show Gist options
  • Save martinrue/95934a12a18fb0816c62bfb6424c2692 to your computer and use it in GitHub Desktop.
Save martinrue/95934a12a18fb0816c62bfb6424c2692 to your computer and use it in GitHub Desktop.
The new TypeScript `satisfies` operator.
/*
The satisfies operator, introduced in TS 4.9, enforces
a constraint on a value without changing the inferred
type. It's super useful when you want to keep the most
specific type that can be inferred.
*/
type Data = {
value: number | string;
};
const foo: Data = {
value: 42,
};
// typeof foo.value is number | string (even though we *know* it's a number)
const foo = {
value: "42",
} satisfies Data;
// typeof foo.value is now a string (the most specific type is inferred)
const foo = {
va1ue: "42"
};
// You may be thinking, "Why even use satisfies? If I leave it off, foo.value is still a string."
// The answer: now foo has no type constaint at all. What if value is misspelled?
// You may have noticed *it is* misspelled, but TS doesn't care.
// However:
const foo = {
va1ue: "42"
} satisfies Data;
// Here the TS type checker correctly stops us misspelling value.
// We get the type constraint, as well as the most specific type.
// Win-win.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment