Stylesheets in React Native with TypeScript Revisited
I’ve already written an article about this topic around one year ago. Now it’s time to revisit it with new information. This time we’ll cover passing styles as props.
We have a Button component with a possibility to override default styling with optional props:
Let’s focus on L:35 and L:37. They include styling for button wrapper and the label. They’re arrays with default styling (styles.button / styles.label) and additional styling with optional properties. These props are at the moment defined as any.
Proper definition of Styles
Like in previous article, we will define ViewStyle, TextStyle and ImageStyle. These will protect style definitions and prompt us if incorrect style property is used.
In addition, we’ll add a StyleProp which is used for defining correct styling in props:
You should notice that we’ve made two changes: defining the interface for Styles (L:20 — L:24) and adding StyleProp<T> (L:16, L:17) for incoming style props.
TypeScript compiler (and IDE with correct setup) is aware what kind of style properties Button component actually accepts.
The Outcome
Let’s try it:

As you can see, everything seems to be in order. Wrapper (as ViewStyle) accepts new backgroundColor and label (as TextStyle) accepts both color and textAlign.
How about if we try this:

As you can see, our IDE (VSCode) will immediately prompt us that text align is incorrect in a style property for ViewStyle.
But Why All the Effort?
Why to spend time on this kind of nitpicking? Every developer can probably see on the device that their styling is failing and then fix the problem. Doesn’t it take more time on writing these declarations rather than spotting them live?
My personal opinion: everyone should follow these whenever possible. I’ve been in several projects — either with TypeScript or Flowtype.
If I have had a possibility to start the project from scratch, I’ve taken care that these rules and guidelines exists in the code. No fellow developer has ever complained. And if I’ve joined an ongoing project which doesn’t properly take care of type checking, then the team have spend small effort to implement it. It has paid us back in many ways — even this kind of “micro polishing”.

