3

How is a boolean value (true or false) not an invalid value for a prop of type React.ReactNode, resulting in the following being a Typescript error?

interface IProps {
    node: React.ReactNode;
}

const foo: IProps = {
    node: false,
};

1 Answer 1

5

ReactNode represents all the possible values that can be put as a child of an element. Booleans are allowed because the following is a very common pattern for doing conditional rendering:

const condition: boolean = Math.random() > 0.5;

<div>
  {condition && (
    <p>You win!</p>
  )}
</div>

If condition is false, then the div's children prop will be false, and so the type is set up to allow this.

If you only want to allow elements, consider using React.ReactElement instead:

interface IProps {
   node: React.ReactElement;
}

const foo: IProps = {
  node: <div /> // Good
}

const foo2: IProps = {
  node: null // Error. If you want to allow null, change to React.ReactElement | null
}

const foo3: IProps = {
  node: false // Error
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.