Types Deep Dive 10 exercises
Problem

Strongly Typing Children in React

The ability to strongly type children in React is a highly requested feature.

Sometimes you only want certain types of children to be passed to your components.

For instance, consider a Select component. Ideally, the only children we want to pass to it are Option components.


co

Loading exercise

Transcript

00:00 In this exercise, we're going to look at something that's a really strongly requested feature of React and TypeScript, which is strongly typing children. Sometimes you only want certain types of children to be passed to your components. Here we have a select component, and ideally the only children we want to admit to it are option components.

00:19 Here I've sort of got it working, but I really haven't. I've got an option component, and this option component, instead of returning JSX.element, it returns an option type. And here, if I kind of like remove this, it would just return JSX.element instead, but instead it returns option type. Very cool.

00:38 Option type is like a special type where it's a Reactor node, but it's also a special branded type. And this branded type is kind of like an impossible type. We're not supposed to be able to actually put it out in the real world, right, or in the runtime.

00:54 This brand here kind of doesn't exist here, and we're having to use as in order to actually make it work. So you should think of this as kind of like we're forcing this to be a option type, when in fact at runtime, it's just going to behave the same as a JSX.element.

01:11 And then inside the select, we actually basically say, okay, here we've got some option types. Those are the only thing you can pass into the children. But we've got an error here, which is that brand is missing in type React element, but required in type brand option type. So that's your job.

01:29 Try to figure out really what option type is all about. See if what we're doing is even possible. And also try changing option to this syntax. And this seems to work. Why would this work? And why would the other thing not work? Good luck.