[Typescript] Tips: Throw detailed error messages for type checks
You can throw detailed error messages for type checks. Here, I move a runtime check in a function to the type level, meaning you get a detailed error if you use it wrong.
const deepEqualCompare = <T extends any>(
a: T, b: T
): boolean | Error => {
if (Array.isArray(a) || Array.isArray(b)) {
throw new Error("You cannot compare two arrays using deepEqualCompare")
}
return a === b
}
deepEqualCompare(1, 1)
deepEqualCompare([], ["a"])
Using type check:
export type checkForBadArgs<Arg> = Arg extends any[]
? "You cannot compare two arrays using deepEqualCompare"
: Arg;
const deepEqualCompare = <T extends any>(
a: checkForBadArgs<T>, b: checkForBadArgs<T>
): boolean | Error => {
if (Array.isArray(a) || Array.isArray(b)) {
throw new Error("You cannot compare two arrays using deepEqualCompare")
}
return a === b
}
deepEqualCompare(1, 1)
const res = deepEqualCompare([], ["a"]) // type error