Advanced Props 12 exercises
Problem

Conditionally Require Props With Discriminated Unions

In this exercise, we have a standard Input component with a clever twist in its prop types:


type InputProps = (
| {
value: string
onChange: ChangeEventHandler
}
| {}
) & {
label: string
}
export const Input = ({ label, ...props }: InputProps) => {
return (

Loading exercise

Transcript

00:00 In this exercise, we have an input component. And this input component is a very standard input component, except we've gotten a bit clever in the prop types. We want to basically have two different states for our components. Either it's going to be a controlled component where we're going to pass in value and onChange,

00:18 or it's going to be an uncontrolled component where we pass in neither of those. We can pass in things like maybe default value or something. But currently the only other required prop is this label string here. Now, this label string, as we can see, is present on both of them. I've just added it in for a little bit of complexity.

00:36 But there are some tests that are failing here. Nothing seems to be wrong inside the input component, but there's some bad stuff happening here. So we have our label greeting, which is present on all of these, and we have value hello and onChange up here. That's working nicely.

00:52 Except here, it's not erroring when we only pass the value. It's not erring when we only pass the onChange too. So your job is to work out how we can properly get like all of these props or none of these props situation happening. I'll give you a clue.

01:09 It's all about changing this line of code here, expanding this out maybe and adding a couple more properties to it. Because we know based on the explainer in this section that this is not doing what we think it's doing in this position. Good luck.