Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using functions within React Native StyleSheet with Typescript

Often times I want to do something like

const styles = StyleSheet.create({
  square: (size: number) => ({
    width: size,
    height: size,
  }),
})

Now this doesn't work, because I get Type '(size: number) => { width: number; height: number; }' is not assignable to type 'ViewStyle | TextStyle | ImageStyle'. I've tried doing things like

interface Style {
  square: (width: number) => ViewStyle
}

const styles = StyleSheet.create<Style>({
  square: (size: number) => ({
    width: size,
    height: size,
  }),
})

But then I get Type 'Style' does not satisfy the constraint 'NamedStyles<any> | NamedStyles<Style>'.

Any ideas how to deal with this?

like image 584
Kristjan Vool Avatar asked Aug 14 '26 14:08

Kristjan Vool


1 Answers

StylesSheet doesn't support using fuctions but you can use an Object or a Function instead and type the return value with one of these types ViewStyle | TextStyle | ImageStyle

E.g

const styles = {
    square: (size: number): ViewStyle => ({
        width: size,
        height: size,
    })
};
like image 76
Daniel Gabor Avatar answered Aug 16 '26 17:08

Daniel Gabor