Home > Mobile >  Type Script - React Native: " ViewStyle " type issue
Type Script - React Native: " ViewStyle " type issue

Time:08-28

When I pass the parameter:

defaultButtonTextDark: {
     fontWeight: 'bold',
     color: 'white',
     fontSize: 16,
   },

into ThemeManager function :

const ThemeManager = (darkStyle: ViewStyle, lightStyle: ViewStyle) => {
  DO SOMETHING...
}

So it shows me the following error:

Type '{ fontWeight: "bold"; color: string; fontSize: number; }' has no properties in common with type 'ViewStyle'.ts(2559).

way of use the function:

<Text style={ThemeManager(styles.defaultButtonTextDark, styles.defaultButtonText)}>return default</Text>

What is the way to solve this type issue ?

CodePudding user response:

The ViewStyle type has no properties named color, fontWeight or fontSize.

It seems to me that you have a function named ThemeManager that returns a style meant for a Text component.

The type for the style prop of a react-native Text is defined in TextStyle.

Thus, the correct typing is as follows:

const ThemeManager = (darkStyle: TextStyle, lightStyle: TextStyle) => {
  DO SOMETHING...
}

However, depending on how you have defined the type for defaultButtonTextDark, you might get troubles when it comes to the typing of fontWeight which has the following type:

'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'

To fix this, we could provide the type explicitly here.

const defaultButtonTextDark: TextStyle = {
     fontWeight: 'bold',
     color: 'white',
     fontSize: 16,
} 

On the other hand, if defaultButtonTextDark is defined in a StyleSheet, then you do not have these problems:

const styles = StyleSheet.create({
  defaultButtonTextDark: {
    fontWeight: 'bold',
    color: 'white',
    fontSize: 16,
  },
});
  • Related