Typescript in React-Native
Creating A React-Native/Typescript Project
In a previous article I went over how to create a regular React-Native app using Expo. This process follows similar guidelines except that you will choose the second option after entering expo init which will be a blank typescript template.
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
So far there is not a whole lot of typescript going on in this project. Also if we started to do anything simple we seem to introduce typescript errors very easily. For instance if we were to create a simple Home screen and an Options screen that just shared a link to each other we start getting typescript errors on their props like so:
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:
You should now also notice Typescripts tooling in action when you provide a string argument to navigate which will look like this:
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!