React Native and TypeScript meets Styles

Samuli Hakoniemi
Jan 23, 2018 · 2 min read

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:

import { StyleSheet, Text, TextStyle, View, ViewStyle } from ‘react-native’;

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

interface Styles {
wrapper: ViewStyle;
textContent: TextStyle;
}

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:

Types of property ‘closeButton’ are incompatible.
Type ‘{ textAlign: string; zIndex: number; }’ is not assignable to
type ‘ViewStyle’.
Object literal may only specify known properties, and ‘textAlign’
does not exist in type ‘ViewStyle’.

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

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.

Samuli Hakoniemi

Written by

In a serious relationship with React Native

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade