Unlock the Power of TypeScript in Your React Native Apps

What is TypeScript?

TypeScript is an open-source language built on top of JavaScript by Microsoft. Think of it as JavaScript, but with static type definitions. This means you can enjoy better documentation, error reduction, and easier adoption, all while still compiling to JavaScript.

Why Choose TypeScript?

If you’re still unsure about giving TypeScript a try, here are a few compelling reasons to consider:

  • Better documentation: Clearly defined types make it easy to reference other parts of your code.
  • Error reduction: TypeScript validates your code before execution, saving you time and frustration debugging errors.
  • Easy adoption: You can start using TypeScript in your existing JavaScript applications, one file at a time.

Building a Shopping List App with React Native and TypeScript

Now that we’ve covered the basics, let’s dive into building a shopping list application using React Native and TypeScript. This project is designed to showcase the benefits of TypeScript without getting too complex.

Getting Started

To begin, run the following command in your terminal:

npx react-native init ShoppingList --template react-native-template-typescript

This will set up a new React Native project using a TypeScript template.

Building the Base UI

Open the project folder in your code editor and run the following commands to start the project:

npx react-native start
npx react-native run-ios

Create a Header.tsx component in the src/components folder and paste the following code:


interface Props {
  title: string;
}

const Header: React.FC<Props> = ({ title }) => {
  return <>
    {title}
  </>;
};

export default Header;

Notice how we’re defining the Props interface and specifying the type of the title property? This is where TypeScript shines, providing better IntelliSense and validation.

Adding Items to the List

Create an AddItem.tsx component and paste the following code:


interface IItem {
  id: number;
  title: string;
}

const AddItem: React.FC<{
  onAddItem: (item: IItem) => void;
}> = ({ onAddItem }) => {
  const [title, setTitle] = useState('');

  const handleAddItem = () => {
    if (title) {
      onAddItem({ id: Date.now(), title });
      setTitle('');
    }
  };

  return (
    <>
      <<>
        Add Item
      </>
      <input
        type="text"
        value={title}
        onChange={(e) => setTitle(e.target.value)}
        placeholder="Enter item title"
      />
      <button onClick={handleAddItem}>Add</button>
    </>
  );
};

export default AddItem;

We’re defining the IItem interface and using it to specify the type of the onAddItem prop.

Listing Out Items

Create an Item.tsx component and paste the following code:


interface Props {
  item: IItem;
}

const Item: React.FC<Props> = ({ item }) => {
  return (
    <>
      {item.title}
    </>
  );
};

export default Item;

We’re using the IItem interface to specify the type of the item prop.

Finishing Up the App

Replace the content of App.tsx with the following code:


import React, { useState } from 'eact';
import { FlatList } from 'eact-native';
import AddItem from './AddItem';
import Item from './Item';

const App = () => {
  const [shoppingList, setShoppingList] = useState<IItem[]>([]);

  const handleAddItem = (item: IItem) => {
    setShoppingList([...shoppingList, item]);
  };

  return (
    <>
      <AddItem onAddItem={handleAddItem} />
      <FlatList
        data={shoppingList}
        renderItem={({ item }) => <Item item={item} />}
      />
    </>
  );
};

export default App;

Our app is now complete! We’ve successfully used TypeScript to define interfaces, specify prop types, and catch errors before they happen.

Take Your TypeScript Skills to the Next Level

This article has only scratched the surface of what’s possible with TypeScript in React Native applications. Take the next step by implementing features like removing items from the list, and explore the official TypeScript documentation for more information.

Leave a Reply