The Weird Parts of TypeScript 13 exercises
solution

Handling Union of Functions with Incompatible Types in TypeScript

In TypeScript, a union of functions that each accepts a different type of input can yield the never type. This occurs when no single input type can simultaneously fulfill different type requirements.

For example, creating an Input type that is a string, number, and boolean at the same time reso

Loading solution

Transcript

00:00 Okay, the key to figuring this out is if we look at this formatter, we can see that the formatter is resolved as input never is a string or returns string. What? How could input be never at this position? Well, if we know what we know about unions of functions,

00:18 and this is a union of functions, one of which takes input string, one of which takes input number, one of which takes input Boolean, we know that in order to satisfy that, you need to intersect those input types together. So we can say type input is string and number and Boolean. Then if we hover over inputs, we're going to see that that resolves to never

00:37 because something cannot be both a string and a number. It cannot be both a number and a Boolean. So it resolves to never. Now we know though, that this formatter is going to be called with the right thing. It's going to be called with the right thing. At runtime,

00:54 this code actually works. And so what you end up needing to do is that this is the crazy thing about this bug is you can't say as any, because any does not seem to be assignable to parameter of type never, it was expecting never, but he passed any. So as any actually

01:11 doesn't work here. So what you've got to do is say as never. This is something that actually comes up quite a lot. And I've seen this occur in the wild a fair bit. So as never has a kind of like a union of functions handling that makes the most sense. The other way of

01:29 course is to do it kind of by changing your runtime code, which is to say if type of input equals string, then you call object of functions.string input. And of course, input at that point has been narrowed to a string. And so it's not going to be resolved as never. But of course,

01:44 this is just more code actually, and just not as tight and as compact as this code, which I think we'll just compile down a bit better. And we're really using JavaScript's polymorphism to its maximum capacity. So input as never, when you have functions with incompatible

02:03 type signatures being union together, you're sometimes going to need to use as never in these situations to get yourself out of a bit of bother.