Skip to content

Instantly share code, notes, and snippets.

@temoncher
Last active May 22, 2024 11:32
Show Gist options
  • Save temoncher/f55faab8f385129e3d0be7bd159848c9 to your computer and use it in GitHub Desktop.
Save temoncher/f55faab8f385129e3d0be7bd159848c9 to your computer and use it in GitHub Desktop.
Example of descriptive type errors instead of `never`s
declare const errorTag: unique symbol;
type TypesError<T> = { [errorTag]: T };
interface Validatable {
validate(): boolean;
}
type Assert<T, TType, TTypeName extends string, TTargetName extends string = string, TSource extends string = string> = T extends TType ? T :
string extends TTargetName
? TypesError<`T should be of type {${TTypeName}}`>
: string extends TSource
? TypesError<`{${TTargetName}} should be of type {${TTypeName}}`>
: TypesError<`{${TTargetName}} in {${TSource}} should be of type {${TTypeName}}`>;
type Assert_acceptValidatable<T> = Assert<T, Validatable, "Validatable", "target", "acceptValidatable(target)">
function acceptValidatable<T>(target: T): Assert_acceptValidatable<T> {
return target as Assert_acceptValidatable<T>;
}
const res = acceptValidatable({ validate: () => 'string' });
// ^?
// TypesError<`{target} in {acceptValidatable(target)} should be of type {Validatable}`>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment