Skip to content

Conversation

williamsjokvist
Copy link

@williamsjokvist williamsjokvist commented Jul 14, 2025

This eases the style param typing for all components, allowing [Style[], undefined, Style] etc. to be passed. Which is a common pattern in e.g. React Native.

Desired behavior:

function PaddedView({ style, ...rest }: ViewProps) {
  return (
    <View
      style={[
        {
          padding: 12,
        },
        style
      ]}
      {...rest}
    />
  )
}

Before this would give an error, despite the JS working fine.

Type 'Style | Style[] | undefined' is not assignable to type 'Style'.
Type 'undefined' is not assignable to type 'Style'.

To circumvent this, I've seen people do these cumbersome runtime checks, which is not necessary with vanilla JS:

function Root({ style, ...rest }: ViewProps) {
  return (
    <View
      style={[
        {
          padding: 12,
        },
        ...(Array.isArray(style) ? style : [style ?? {}])
      ]}
      {...rest}
    />
  )
}

In my own projects I've added this piece of module augmentation, which is the typing included in this PR:

declare module '@react-pdf/renderer' {
  interface RecursiveArray<T>
    extends Array<T | ReadonlyArray<T> | RecursiveArray<T>> {}

  type StyleProp<T> = T | RecursiveArray<T | undefined>;

  interface ViewProps {
    style?: StyleProp<Style | Style[]>;
  }
  ...
}

Copy link

changeset-bot bot commented Jul 14, 2025

⚠️ No Changeset found

Latest commit: 368655e

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

@tifye tifye left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me

@williamsjokvist williamsjokvist force-pushed the fix/ease-style-param-typing branch from d079cb4 to 368655e Compare July 14, 2025 22:29
@williamsjokvist williamsjokvist changed the title fix(types): ease style param typing fix(types): allow recursive array of styles Jul 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants