When to use TypeScript's `never` type

04/13/2021 , 2m, 58s

Hey friends So last night I tweeted this TypeScript question. When have you used never in a production codebase links to examples welcome? And I failed to mute the conversation and so I ended up waking up the next morning with tons of notifications, which was great. So many people were happy to share and I just wanted to share with you a couple or the like basic themes of the different examples that people shared.

So the first is discriminating union. Oh and by the way, if you've never heard of never before the basic idea is it's a way for you to say.Hey the type script type checker as it's flowing through the types of my application, it should never be able to hit this type.

So it's like those situations where you like this should never happen. That's basically when you use never. So anyway, the first is discriminating unions and a common example for this was if you had a component that could take a variety of different props. So an example is a component that could like draw a shape so you could be rectangle or a square or a circle and depending on the type of shape you want to draw you're going.

To have different props And so square will have a width Rectangle will also have a height in addition to that. And then circle won't have either of those it'll have like a diameter something. So the you know, the discriminating union's use case for never would be when you union those props together you want to be able to say hey when it's a circle I never want to have a height or a width and when it it's a square.

I never want to have a height because I just get it from the width and I never want to have a diameter because it's not a circle. In my mind,Actually most of the examples were similar to that and in my mind most of the time you're actually probably better off just making two separate components or yeah different components entirely that are responsible for doing that specific thing.

However, sometimes there are definitely use cases for you know, if if you're going to provide me this prop, you also must provide me this prop, but if you provide this other one, then you must not provide this this other. So like aria described by versus already described stuff like that.

So that was like the primary use case in addition.Switch out ifs and else statements this is where you can make a function that is basically they would call it a certain ever and it would return never it would throw an error. And basically your time typescript well by calling that function you get a type error.

And so if you put this as the default case or something and you're not handling every case then type script is going to cause a problem for you. And then the last one was conditional types and that one still pretty hazy for me. I can't really explain it. So anyway, hopefully some of that was interesting.

And I hope you have a wonderful day. Bye.