Throw detailed error messages for type checks

Using a crazy trick I picked up from @AndaristRake, 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.

Discuss on Twitter

Transcript

You can use TypeScript to throw some absolutely crazy errors at the type level, even without touching the runtime code at all. Here in our deepEqual compare function, we use this A triple equals B, which is really good for comparing primitives like 1 and 1, for instance, or a string to another string.

It's really not very good at comparing two arrays. This will always return false, for instance, even if it's like this because this first array is not the same element as the other array. We can actually move this to the type level by saying, first of all, we're going to say, "Check for bad args."

We're going to say, "This is going to be generic. The arg is going to be like this." We're going to say arg extends any array." We're going to say, "You cannot compare two arrays using deepEqual compare." We're just going to copy and paste that in.

Otherwise, we're going to return the arg. We're going to use this in the function arguments here. We're going to say, "Check for bad args here and check for bad args there." Now, what you'll see is that here, argument of type never is not assignable to parameter of type.

You cannot compare two arrays using deepEqual compare. We actually managed to move this to the type level.

More Tips