`satisfies` is my favorite TypeScript keyword
24 points by runxiyu
24 points by runxiyu
My mental model is that x satisfies y checks that the type of x matches the type y wherever this check is placed.
Thus, satisfies also simplifies exhaustiveness check in a switch statement. What used to be:
switch(x) {
// other cases
default:
const exhaustiveCheck: never = x;
throw new Error(`Unknown case: ${exhaustiveCheck}`);
}
now becomes:
switch(x) {
// other cases
default:
// At this point, type of x is supposed to match the type `never`.
// If it doesn't, then (x satisfies never) portion produces a compile-time error.
// (throw x) portion ensures a runtime error too.
throw x satisfies never;
}
Of course, this being TypeScript, there might be yet another better way already to check exhaustiveness. If so, then feel free to correct me!
throw-ing in the default case is indeed usually a good idea, just in case something happened elsewhere that went against the type system. However, it's often better to throw things of type Error than it is to throw some unknown type. This can be accomplished with a simple wrapper class:
export class UnreachableError extends Error {
constructor(value: never) {
super(`Unreachable: ${inspect(value)}`);
this.name = "UnreachableError";
}
}
Nice one! I agree about throwing an Error that wraps a value instead of throwing the value itself.
Not familiar with TS, but I've been looking into discriminated unions lately, sounds like satisfies could be used to prevent the tag from widening into a generic type from the options representable in the discriminated union
satisfies never affects the inferred type so it’s not helpful with that. If you ever need an object literal to keep the type of the discriminated union tag more narrow, you would use as const.
This seems like a timely place to ask: is anyone else unable to get satisfies syntax highlighting in Sublime Text? I don't know enough about Sublime's internals to get it working myself, but earlier today I took a look at the Packages/TypeScript Syntax/TypeScript.tmLanguage that ships with the current Sublime build, and it doesn't mention satisfies at all.
You’re generally gonna have a much better time doing typescript in something else like vscode. Not a lot of people are doing TS in sublime.
I use both sublime and vscode daily, but all my ts is in vscode.
The satisfies operator is available since TypeScript 4.9.0 (source: https://devblogs.microsoft.com/typescript/announcing-typescript-4-9/).
Sublime Text 4 should support proper highlighting, but searching the topic it seems TS highlighting is still buggy in Sublime.