TS Declaration for passing StyleSheet parameters

Viewed 55

I'm trying to find a way to make TypeScript accept passing variables to StyleSheet

Exemple:

<View style={[styles.foo(isVisible), styles.bar]} />

...

export default StyleSheet.create({
  foo: (isVisible: boolean) => ({
    opacity: isVisible ? 1 : 0
  })
  bar: {
    // something
  }
})

I tried to redeclare StyleSheet.create with the code below but I can't find a solution. Any idea ?

import 'react-native'

declare module 'react-native' {
  namespace StyleSheet {
    type Style = ViewStyle | TextStyle | ImageStyle
    type NamedStyles<T> = { [P in keyof T]: Style }

    export function create<T, S extends NamedStyles<S> | NamedStyles<any>>(
      styles: T | NamedStyles<S>,
    ): T & S
  }
}
1 Answers

You could just turn your StyleSheet constant into a function and pass optional props to it with explicit typing as follows.

type StyleSheetProps = {
  isVisible?: boolean
}

const styles = (props?: StyleSheetProps) =>
  StyleSheet.create({
    opacityStyle: props?.isVisible ? 1 : 0
  })

And then use it as follows.

<View style={[styles({isVisible: foo.isVisible()}).opacityStyle, styles().bar]} />
Related