Last active
May 22, 2024 11:32
-
-
Save temoncher/f55faab8f385129e3d0be7bd159848c9 to your computer and use it in GitHub Desktop.
Example of descriptive type errors instead of `never`s
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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