Advanced Patterns 11 exercises
Problem

Records of Components with the Same Props

A common pattern in React involves having multiple components that all require the same set of props, which are usually defined by a parent component that wraps all the child components together.

Here's an example:


type InputProps = React.ComponentProps<"input">;
const COMPONENTS =

Loading exercise

Transcript

00:00 In this exercise, we're going to look at a pattern which is pretty common in React apps where you have a bunch of components that all take in the same props, and you want to specify them via a variant or something, by a parent component that wraps them all together. Here we have a set of components, like a record of components,

00:18 where we have text, number, and password, and they all take in the same props. They all take in input props that we're grabbing from React.ComponentProps here. So I could, if I wanted to, just say input props like this, and things would start working. Now, though, we have this input down here,

00:36 and this input is supposed to take in various different types down here, and these types correspond to the components that we want to render. So we have type number, type text, and type password, and we want one to be inferred from the other.

00:53 Now, I don't really want to have to type input props or props input props for each component, because that's going to get pretty annoying if we have 20 of these, and we need to keep them all in sync. So your job is to try to find a way that I can strongly type this, and strongly type this to satisfy all of this stuff down here, because I want to make sure

01:13 that my onChange is properly typed. I want to make sure that type text, type password, all receive the right stuff, and I want to make sure that it's erroring if I pass in the wrong type down there. And so you are going to find that record and satisfies is probably going to be pretty useful to you. And the main way is just to solve this unknown type

01:32 and to add a new annotation to this components type here. Good luck.