In my React-Native project, I'm focusing on implementing autocomplete and type validation. One of the challenges I'm facing is configuring the types for the stylesheet library I am using.
A customized stylesheet is structured like this:
const styles = createStyles({
variable1: 100,
variable2: "10rem",
header: {
width: "100%",
height: 40,
alignContent: "center",
flex: "$flexAll",
margin: "$gapMD"
}
})
Each style value in the defined styles should not only accept its original type but also a string
, function
, etc.
After processing the stylesheet, the output is a standard React-Native stylesheet. Therefore, the function result should retain the same properties as the input, mapping them to the original style types.
For example, the property flex
should be strictly a number
, not a ambiguous union like
number | string | function | etc.
This is the current progress:
import { ImageStyle, TextStyle, ViewStyle } from "react-native"
import EStyleSheet from "react-native-extended-stylesheet"
type Function<K> = () => K
type AllStyles = ImageStyle & TextStyle & ViewStyle
type StyleSet<T> = { [P in keyof T]: AllStyles }
type EValue<T> = T | string & {}
type EVariable<K> = EValue<K> | Function<EValue<K>>
type EStyle<T> = { [P in keyof T]: EVariable<T[P]> }
type EAnyStyle = EStyle<ImageStyle> | EStyle<TextStyle> | EStyle<ViewStyle>
type EStyleSet<T> = { [P in keyof T]: number | string | EAnyStyle | EStyleSet<T> }
export const createStyles = <T>(styles: EStyleSet<T>) =>
EStyleSheet.create(styles) as StyleSet<T>
Unfortunately, the autocomplete feature is not fully functional, and I sense that my definitions are becoming overly complicated. Moreover, the resulting type is not entirely accurate.
If there's a TypeScript expert out there who can assist me in resolving this issue, it would be greatly appreciated.
I've created a Sandbox where you can test some of the types:
https://codesandbox.io/s/typescript-style-mania-h62cv