Here is the style I’m using and how I’m using it
style={styles.input(isPasswordSelected)}
const styles = StyleSheet.create({
input: (isPasswordSelected: boolean) => ({
height: 40,
marginHorizontal: 20,
marginVertical: 7,
padding: 10,
borderRadius: 10,
backgroundColor: '#c9c9c9',
borderWidth: 1,
borderColor: isPasswordSelected ? '#458ae6' : 'transparent',
}),
});
This normally works in JS without issues but in ts I get this error
Type ‘(isPasswordSelected: boolean) => { height: number; marginHorizontal: number; marginVertical: number; padding: number; borderRadius: number; backgroundColor: string; borderWidth: number; borderColor: string; }’ is not assignable to type ‘ViewStyle | TextStyle | ImageStyle’.ts(2322)
it seems to think that the entire function is my type declaration.
The error is just in the IDE, code runs fine. Possibly able to solve with an update to my tsconfig.json
I’ve tried changing the typing to style typings but couldn’t get the error to go away
2
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
another way is to bypass this issue using StyleSheet.create < any > :
but this way you lost typing of other properties check demo :
https://snack.expo.dev/BDj-VZJm5
but as i mentioned before you can use an Object or a Function instead and type the return value with one of these types ViewStyle | TextStyle | ImageStyle :
and the best way is to use the old school method
Functions aren’t a valid part of a StyleSheet. There are many ways of doing this. The most common way is to assign the styles statically in your StyleSheet and then compose them dynamically in your JSX:
You can also make your styles a function that returns a StyleSheet: