2

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
  }
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
tinmarfrutos
  • 1,740
  • 1
  • 14
  • 23

1 Answers1

0

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]} />
David Scholz
  • 8,421
  • 12
  • 19
  • 34
  • Thanks for your answer. I don't really like this solution because if you have a lot of style in a file, your props will be too large and it's not very readable. Ideally, I would like to keep the writing format I shared – tinmarfrutos Mar 10 '22 at 11:07