1

I try to use some variables inside my StyleSheet file.

The UI is working fine. But the type is error.

Any idea how to solve this?

type buttonStyle = (height: number, width: string, color: string) => ViewStyle;

export type Styles = {
  button: buttonStyle;
};

export default StyleSheet.create<Styles>({
  button: (height: number, width: string, color: string) => ({
    height: height,
    width: width,
    backgroundColor: color,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 10,
  }),
});

This is the error message from type.

Type 'Styles' does not satisfy the constraint 'NamedStyles<any> | NamedStyles<Styles>'.
  Type 'Styles' is not assignable to type 'NamedStyles<Styles>'.
    Types of property 'button' are incompatible.
      Type 'buttonStyle' is not assignable to type 'ViewStyle | TextStyle | ImageStyle
TylerH
  • 20,799
  • 66
  • 75
  • 101
Ganda Rain Panjaitan
  • 833
  • 1
  • 12
  • 28

3 Answers3

0
export default StyleSheet.create<Styles | any>({
  button: (height: number, width: string, color: string) => ({
    height: height,
    width: width,
    backgroundColor: color,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 10,
  }),
});

add type any like this,

StyleSheet.create<Styles | any>
-1

You can create a const style using StyleSheet.create() outside of your component:

const styles = ((height: number, width: string, color: string)) => StyleSheet.create({
    btn: {
        height: height,
        width: width,
        backgroundColor: color,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 10,
    }
});

and than call it like this in your component:

<Button style={styles(height: height, width: width, color: color).btn} />
lmasneri
  • 589
  • 7
  • 17
-4

I think StyleSheet does not contain function type. So I fix this error with this approach.

style file

import type { ViewStyle } from 'react-native';

const styles = {
  button: (height: number, width: string, color: string): ViewStyle => ({
    height: height,
    width: width,
    backgroundColor: color,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 10,
  }),
};

export default styles;

No need to define the styles type.

Ganda Rain Panjaitan
  • 833
  • 1
  • 12
  • 28