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
