Image for post
Image for post

React Native and TypeScript meets Styles

I recently came across with an information that one can create TypeScript interface for StyleSheet in React Native.

What Shall We Do?

To get things properly rolling, we need to import ViewStyle and TextStyle:

After this we are good to go for defining an interface:

But Why?

Because interfaces are cool and they keep our code consistent. And then we have the power of TypeScript to tell us what we are doing wrong (again).

The consistency is very similar to what we’re used to do with Props and State. And to be honest: handling of StyleSheet in React Native is not perfect (although most of time it’s giving us proper yellow warnings).

Time to Shine

I’ll share some actual code to demonstrate its behaviour with proper styling interface. This is a custom made Modal component:

Now, this is what actually happens on when we make a mistake with style definitions. We receive an error:

And the same error will appear in VS Code as well:

Image for post
Image for post

This is because of ViewStyle which does not accept textAlign as a property since it happens to be a part only of TextStyle.

This all sounds logical and easy. But I’ve seen many times similar kind of misconceptions and human errors with styles in React Native.

Conclusion

Take this to your arsenal. It’s not mandatory but it offers you one more tool to keep your code clean and valid.

Written by

In a serious relationship with React Native

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store