TS typing for style/xstyle prop on component for custom style application #894
-
// Component
const styles = stylex.create({
base: {
color: 'hotpink'
}
})
interface Props
extends Omit<React.HTMLAttributes<HTMLElement>, 'style'>,
React.PropsWithChildren {
// This could be xstyle or some other non-clashing name, it doesn't matter here
style?: StyleXStyles
}
export const Foo = forwardRef<HTMLSpanElement, TextProps>((props, ref) => {
const { style, children } = props
return (
<span
ref={ref}
{...stylex.props(
styles.base,
style,
)}
>
{children}
</span>
)
}) // Consuming
const customStyles = stylex.create({
big: {
fontSize: 123
}
})
// ...
<Component style={customStyles.big}>One</Component>
<Component style={[customStyles.big]}>Two</Component> This follows the pattern from the docs for accepting styles in components, and works great. However, TS flags an issue with the typing.
|
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 3 replies
-
export type StyleXStyles<
CSS extends UserAuthoredStyles = CSSPropertiesWithExtras,
> = StyleXArray<
| null
| undefined
| false
| GenStylePropType<CSS>
| Readonly<[GenStylePropType<CSS>, InlineStyles]>
>; export type StyleXArray<T> = T | ReadonlyArray<StyleXArray<T>>; |
Beta Was this translation helpful? Give feedback.
-
Thanks @predaytor Just tried locally and it works perfectly. Good to clarify I'm typing things correctly. |
Beta Was this translation helpful? Give feedback.
-
This is the offender where the .d.ts is installed in multiple places. |
Beta Was this translation helpful? Give feedback.
-
Thanks for clarifying I'm typing correctly. I'll update the original post from: interface Props
extends Omit<React.HTMLAttributes<HTMLElement>, 'style'>,
React.PropsWithChildren {
// This could be xstyle or some other non-clashing name, it doesn't matter here
style?: StyleXStyles | Array<StyleXStyles>
}
export const Foo = forwardRef<HTMLSpanElement, TextProps>((props, ref) => {
const { style, children } = props
return (
<span
ref={ref}
{...stylex.props(
styles.base,
...(Array.isArray(style) ? style : style ? [style] : []),
)}
>
{children}
</span>
)
}) to interface Props
extends Omit<React.HTMLAttributes<HTMLElement>, 'style'>,
React.PropsWithChildren {
// This could be xstyle or some other non-clashing name, it doesn't matter here
style?: StyleXStyles
}
export const Foo = forwardRef<HTMLSpanElement, TextProps>((props, ref) => {
const { style, children } = props
return (
<span
ref={ref}
{...stylex.props(
styles.base,
style
)}
>
{children}
</span>
)
}) as this change was not the problem (funky installation was) and its clearer to have the intended code in the post. |
Beta Was this translation helpful? Give feedback.
StyleXStyles
is already accepts arrays by default, wdym?