Typescript in React-Native

Introduction

Creating A React-Native/Typescript Project

Here is a snap shot of the option you should select

Once this finishes go ahead and navigate into your new project folder and open your text editor. You will notice that the usual .js file extensions have been replaced with typescripts .tsx and that you have a .tsconfig file in your projects root directory. Before we continue I’d like to mention I’m oddly particular in how I setup my file structure so if it looks different than yours in the following pictures feel free to mimic my setup by following the guidelines of this article. Now lets look at some of the features we have unlocked with typescript!

Initial Typescript Errors and Typing

This brings us to one of the advantages Typescript brings to React Native: You can define a type that provides all of your linked routes meaning you will be assured what it is called when trying to link to it. And also you can define a type that defines the props for any given component. Lets first create our MainStackParamList type in order to define our props for any given screen we will use. Within App/constants create types.tsx and have it export a type of MainStackParamList with keys for each of your screens and values of undefined like so:

Now within Navigation.tsx we can import our new MainStackParamList type and use it to correspond with our createStackNavigator function like so:

We can then go in to one of our screens (This time Home) and import NativeStackScreenProps from ‘@react-navigation/native-stack’. In order to utilize this type you will also have to install this dependency. Within terminal please enter:

npm i @react-navigation/native-stack

You will also have to import our MainStackParamList. We do this in order to set a type above our component that is of NativeStackScreenProps and MainStackParamList with a key of “Home” like so:

We can then use generics again to set our Home component to a type of React.FC and HomeScreenProps. This gets rid of our pesky prop error!

Conclusion

This article really only scratches the surface but I believe sets some initial basics on how to implement Typescript with React-Native. Feel free to read more on how these two technologies interact in the documentation. Thanks for reading!

--

--

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