Course contentsShow
← React
Lesson 1171 of 2,39630. Composition: Inversion of ControlFree lesson

TypeScript and Prop Getters

Type prop getter return values so consumers get autocomplete for all props the getter provides.

TypeScript and Prop Getters

You'll learn how to type prop getter functions so consumers get full autocomplete and type safety for all the props they provide.

The Core Idea

When you create a prop getter function (like getInputProps() or getToggleButtonProps()), TypeScript users need to know what properties that getter returns. Without proper typing, developers lose autocomplete and can't see what props the getter injects—defeating much of the pattern's convenience.

The solution is to explicitly type the return value of your prop getter functions, defining all the props they'll spread onto elements.

Typing the Return Value

// Define what props the getter returns
interface InputProps {
  value: string;
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  onBlur: () => void;
  'aria-invalid': boolean;
  id: string;
}

function getInputProps(): InputProps {
  return {
    value: state.value,
    onChange: handleChange,
    onBlur: handleBlur,
    'aria-invalid': !isValid,
    id: 'input-id'
  };
}

Now when consumers use {...getInputProps()}, TypeScript knows exactly what props are being spread, enabling autocomplete and type checking.

Handling User Overrides

If your getter accepts user props to merge, type those too:

function getInputProps(userProps?: Partial<InputProps>): InputProps {
  return {
    value: state.value,
    onChange: handleChange,
    ...userProps
  };
}

Using Partial<InputProps> lets users override any prop while keeping full type safety.

Key Takeaway: Type your prop getter return values explicitly so consumers get autocomplete for all injected props—this makes the prop getter pattern truly ergonomic in TypeScript projects.