Skip to content

Instantly share code, notes, and snippets.

@reverofevil
Created April 5, 2021 10:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reverofevil/7dad117e86d2d22835147b4804e4950f to your computer and use it in GitHub Desktop.
Save reverofevil/7dad117e86d2d22835147b4804e4950f to your computer and use it in GitHub Desktop.
Custom type error messages in TypeScript
declare const StaticErrorTag: unique symbol;
type StaticError<E extends string> = { [StaticErrorTag]: E }
type AAndBAreSame<T> = T extends {a: any}
? T extends {b: T["a"]}
? T
: StaticError<"Types of `a` and `b` differ">
: StaticError<"No `a` field">
const f = <T,>(t: T & AAndBAreSame<T>) => {};
f({a: 5, b: 10});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment