liveBook · Manning

Optional prop

As explained in React in Depth

An optional property is an object or component property that may be omitted from a value of its type.

An optional prop is a component property that callers may omit. In TypeScript, mark it with a question mark; the resulting value may be undefined, so defaults and component behavior must account for absence. section 5.2.2 section 5.3.6

Use optional props deliberately when designing reusable component APIs:

  • Keep a prop optional when it adds behavior without being necessary for the component to work; a default value can make omission explicit. section 4.3.1
  • Convert an inherited optional prop to required by omitting it and redefining it, or use a utility type that requires selected keys. section 5.3.6
  • Do not loosen an inherited property directly through interface extension; omit it first, then redefine its broader type. section 5.3.5
  • Treat optionality as part of collaboration and maintenance: explicit prop types distinguish required inputs from optional enhancements. section 4.3

Optional input value

interface StringInputProps extends ComponentPropsWithoutRef<"input"> { value?: string; } export function StringInput(props: StringInputProps) { return <input type="text" {...props} />; } Here, callers may omit value, but any supplied value must be a string. A related component can require the prop by removing the question mark, or broaden the inherited type only after omitting value. section 5.3.5 section 5.3.6

type ButtonProps = ComponentPropsWithoutRef<"button">;
type RequireSome<T, K extends keyof T> = T & Required<Pick<T, K>>
type HoverButtonProps = RequireSome<
  ButtonProps,
  "onMouseOver" | "onMouseMove" | "onMouseOut"
>;

Inspect the RequireSome utility type for requiring selected properties while preserving the rest of the component prop definition. section 5.3.6

How React in Depth covers it

How deep it goes
Explains syntax, defaults, inheritance constraints, and selected-property utilities, while stopping short of runtime behavior internals.
Examples
Uses typed input components, rating and review props, button event handlers, and car properties with defaults.
What it assumes
Assumes React component and TypeScript prop fundamentals, while introducing optionality from interface syntax through utility types.
What you can do after
Build typed React components that distinguish omitted props, defaults, required inputs, and constrained inherited properties.
How it connects
Connects optional props with TypeScript interfaces, React props, union types, interface extension, Omit, and utility types.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React in Depth. The section links point to the parts of the book it draws on.