When trying to get the appropriate styles for my react native app, it says that it does not work for the button styles.
How can I make the type error disappear?
interface TextButtonProps {
buttonStyle?: StyleProp<ViewStyle>;
labelStyle?: StyleProp<TextStyle>;
click: () => void;
text: string;
}
interface Styles {
button: ViewStyle;
icon: ImageStyle;
label: TextStyle;
}
const TextButton: React.SFC<TextButtonProps> = ({ buttonStyle, text, click }): JSX.Element => {
const styles = StyleSheet.create<Styles>({
button: buttonStyle,
});
error:
Type 'StyleProp<ViewStyle>' is not assignable to type 'ViewStyle | TextStyle | ImageStyle'.
Type 'undefined' is not assignable to type 'ViewStyle | TextStyle | ImageStyle'.ts(2322)
TextButton.tsx(13, 3): The expected type comes from property 'button' which is declared here on type 'Styles | NamedStyles<Styles>'
CodePudding user response:
The problem is that buttonStyle
might be undefined
and the method create
doesn't support the value undefined
buttonStyle?: StyleProp<ViewStyle>; // ? means it can be undefined (a.k.a optional)
You have to check that buttonStyle
is not undefined
, you can do so by:
const TextButton: React.SFC<TextButtonProps> = ({ buttonStyle, text, click }): JSX.Element => {
if (!buttonStyle) return; // Or a proper alternative return value
const styles = StyleSheet.create<Styles>({
button: buttonStyle,
});
}
Or if you're 100% sure that at the time of passing the buttonStyle
argument it won't be null
or undefined
, you can use the non null assertion operator !
const TextButton: React.SFC<TextButtonProps> = ({ buttonStyle, text, click }): JSX.Element => {
const styles = StyleSheet.create<Styles>({
button: buttonStyle!, // <--- Here
});
}