APPCODE

Setting Up TypeScript in React Native: A Complete Guide

TypeScript adds robust type checking to your React Native projects, helping catch errors early and improving code maintainability. This guide will walk you through setting up TypeScript in both new and existing React Native projects.

1. Starting a New React Native Project with TypeScript

bash
# Using React Native CLI
    npx react-native init MyApp --template react-native-template-typescript

    # Using Expo
    npx create-expo-app MyApp --template expo-template-blank-typescript

2. Adding TypeScript to an Existing React Native Project

bash
# Install required dependencies
    npm install -D typescript @types/jest @types/react @types/react-native @types/react-test-renderer

    # Create a tsconfig.json file
    touch tsconfig.json

3. Configure tsconfig.json with React Native Specific Settings

json
{
      "compilerOptions": {
        "target": "esnext",
        "module": "commonjs",
        "lib": ["es2017"],
        "allowJs": true,
        "jsx": "react-native",
        "noEmit": true,
        "isolatedModules": true,
        "strict": true,
        "moduleResolution": "node",
        "baseUrl": "./",
        "allowSyntheticDefaultImports": true,
        "esModuleInterop": true,
        "skipLibCheck": false,
        "resolveJsonModule": true
      },
      "exclude": [
        "node_modules",
        "babel.config.js",
        "metro.config.js",
        "jest.config.js"
      ]
    }

4. Setting Up Essential Type Definitions

typescript
// types/environment.d.ts
    declare module '*.png';
    declare module '*.jpg';
    declare module '*.json';

    // types/navigation.d.ts
    export type RootStackParamList = {
      Home: undefined;
      Profile: { userId: string };
      Settings: undefined;
    };

    declare global {
      namespace ReactNavigation {
        interface RootParamList extends RootStackParamList {}
      }
    }

5. Creating Type-Safe Components

typescript
import React from 'react';
    import { View, Text, StyleSheet, ViewStyle, TextStyle } from 'react-native';

    interface CardProps {
      title: string;
      description?: string;
      style?: ViewStyle;
    }

    const Card: React.FC<CardProps> = ({ title, description, style }) => {
      return (
        <View style={[styles.container, style]}>
          <Text style={styles.title}>{title}</Text>
          {description && <Text style={styles.description}>{description}</Text>}
        </View>
      );
    };

    interface Styles {
      container: ViewStyle;
      title: TextStyle;
      description: TextStyle;
    }

    const styles = StyleSheet.create<Styles>({
      container: {
        padding: 16,
        borderRadius: 8,
        backgroundColor: '#ffffff',
        shadowColor: '#000000',
        shadowOpacity: 0.1,
        shadowRadius: 4,
        elevation: 2,
      },
      title: {
        fontSize: 18,
        fontWeight: 'bold',
      },
      description: {
        marginTop: 8,
        color: '#666666',
      },
    });

    export default Card;

6. Type-Safe Navigation Setup

typescript
import { NavigationContainer } from '@react-navigation/native';
    import { createNativeStackNavigator } from '@react-navigation/native-stack';

    const Stack = createNativeStackNavigator<RootStackParamList>();

    export const Navigation = () => {
      return (
        <NavigationContainer>
          <Stack.Navigator>
            <Stack.Screen name="Home" component={HomeScreen} />
            <Stack.Screen name="Profile" component={ProfileScreen} />
            <Stack.Screen name="Settings" component={SettingsScreen} />
          </Stack.Navigator>
        </NavigationContainer>
      );
    };

    // Type-safe navigation usage
    function HomeScreen({ navigation }: RootStackScreenProps<'Home'>) {
      return (
        <Button
          onPress={() => navigation.navigate('Profile', { userId: '123' })}
          title="Go to Profile"
        />
      );
    }

With this setup, you'll get full TypeScript support in your React Native project, including type checking for components, styles, navigation, and more. TypeScript will help catch common errors early in development and provide better IDE support with autocompletion and inline documentation.

Remember to gradually add type definitions as your project grows. Start with basic Props interfaces for your components and expand to more complex types as needed. Using TypeScript with React Native not only improves code quality but also makes it easier to maintain and refactor your codebase in the future.

TypeScript setup in React Native IDE
TypeScript providing real-time type checking and autocompletion in VS Code