react-spectrum icon indicating copy to clipboard operation
react-spectrum copied to clipboard

`react-aria` should support `exactOptionalPropertyTypes`

Open quisido opened this issue 3 months ago โ€ข 4 comments

Provide a general summary of the feature here

As discussed here:

This would make it much easier to use the library in projects with exactOptionalPropertyTypes enabled. Otherwise, all undefined props passed into React Aria Components throw a type error. Workarounds are ugly. e.g.

<Checkbox
  {...(isIndeterminate === undefined ? {} : { isIndeterminate })}
>
  โ€ฆ
</Checkbox>

๐Ÿค” Expected Behavior?

I expect this code to transpile successfully:

export interface ButtonProps {
  readonly children: string;
  readonly onClick?: VoidFunction | undefined;
}

export default function Button({ children, onClick }: ButtonProps): ReactElement {
  const { buttonProps } = useButton(
    { onClick },
    null,
  );

  return <button {...buttonProps}>{children}</button>;
}

๐Ÿ˜ฏ Current Behavior

Currently, this throws an error:

export interface ButtonProps {
  readonly children: string;
  readonly onClick?: VoidFunction | undefined;
}

export default function Button({ children, onClick }: ButtonProps): ReactElement {
  const { buttonProps } = useButton(
    { onClick }, // โŒ
    null,
  );

  return <button {...buttonProps}>{children}</button>;
}
No overload matches this call.
  The last overload gave the following error.
    Argument of type '{ onClick: VoidFunction | undefined; }' is not assignable to parameter of type 'AriaButtonOptions<ElementType>' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
      Types of property 'onClick' are incompatible.
        Type 'VoidFunction | undefined' is not assignable to type '(e: MouseEvent<FocusableElement, MouseEvent>) => void'.
          Type 'undefined' is not assignable to type '(e: MouseEvent<FocusableElement, MouseEvent>) => void'.ts(2769)

๐Ÿ’ Possible Solution

The interfaces for the react-aria hooks should be defined as property?: X | undefined instead of just property?: X.

๐Ÿ”ฆ Context

I am trying to use react-aria as a dependency in my application that uses exactOptionalPropertyTypes: true.

๐Ÿ’ป Examples

Included above.

๐Ÿงข Your Company/Team

Everyone in the world

๐Ÿ•ท Tracking Issue

N/A

quisido avatar Aug 13 '25 18:08 quisido