📜  react typescript optional props - TypeScript (1)

📅  最后修改于: 2023-12-03 15:04:49.754000             🧑  作者: Mango

React TypeScript Optional Props

When working with React components in TypeScript, you may come across situations where you need to declare optional props. This can be useful for cases where a prop may be needed, but not always required.

Declaring Optional Props

In order to declare an optional prop in TypeScript, you simply add a question mark ? after the prop name in the component's interface. Here's an example:

interface MyComponentProps {
  requiredProp: string;
  optionalProp?: number;
}

function MyComponent({ requiredProp, optionalProp }: MyComponentProps) {
  // ...
}

In this example, optionalProp is declared as an optional prop by adding the question mark ? after the prop name. This means that optionalProp is not required and can be omitted when the component is used.

Using Optional Props

When using a component with optional props, you will need to check if the prop exists before using it. You can use the && operator to conditionally render components depending on whether the prop exists or not. Here's an example:

function MyOtherComponent({ optionalProp }: { optionalProp?: string }) {
  return (
    <div>
      {optionalProp && <p>{optionalProp}</p>}
      {!optionalProp && <p>No optional prop provided.</p>}
    </div>
  );
}

In this example, optionalProp is checked with the && operator before rendering a <p> element. If optionalProp exists, the text of the <p> element will be set to the prop value. If optionalProp does not exist, the <p> element will not be rendered and a message will be displayed instead.

Conclusion

Declaring optional props in TypeScript is a useful technique for making components more flexible and reusable. By adding a question mark ? after a prop name in a component's interface, you can indicate that the prop is not required. When using a component with optional props, you should check if the prop exists before using it in order to avoid runtime errors.