TypeScript with the React Native Ecosystem

Typescript Logo

πŸ“‘ What you will learn

  • Let your computer catch errors as you code and BEFORE you ship bugs to production
  • Create documentation for your team

πŸ‘Ύ Before we start the exercise

TypeScript is fantastic to use with React because it can help us catch a lot of bugs we wouldn't catch otherwise. It helps our team have good documentation and it makes React easier to use.

Typing functionnal components with TypeScript

The main concept of TypeScript is to define the "shape" of our props with types. TypeScript will ensure that everything conforms to the right "shape" in our code.

Here's the interface we are going to use:

interface StarshipCardProps {
  name: string;
  model: string;
  manufacturer: string;
  cost_in_credits: string;
}

πŸ”­ Hint: we are using interface over type because it's more performant during the compilation. But you can use both for now.

Adding Props type

How can we add the "shape" of our component? You probably have something like this

import React from "react";
import { Card } from "react-native-paper";

export function StarshipCard(props) {
  const { name, model, manufacturer, cost_in_credits } = props;
  return <Card>...</Card>;
}

You need to add a new argument to your props declaration. Our component have 4 props name model manufacturer and cost_in_credits.

They are all defined in string because that's what we get from the api.

import React from "react";
import { Card } from "react-native-paper";

interface StarshipCardProps {
  name: string;
  model: string;
  manufacturer: string;
  cost_in_credits: string;
}

export function StarshipCard(props: StarshipCardProps) {
  const { name, model, manufacturer, cost_in_credits } = props;
  return <Card>...</Card>;
}

Destructuring pattern

And because you are killing it, you can use the destructuring pattern like this:

import React from "react";
import { Card } from "react-native-paper";

interface StarshipCardProps {
  name: string;
  model: string;
  manufacturer: string;
  cost_in_credits: string;
}

export function StarshipCard({
  name,
  model,
  manufacturer,
  cost_in_credits,
}: StarshipCardProps) {
  // No extra line here, like in thre previous example
  return <Card>...</Card>;
}

πŸ”­ Hint: Not familiar with destructuring? have a look at the patterns page.

Do you need a translation?

  • I was like you β€”when I started using TypeScriptβ€” feeling lost. You can bookmark the Typescript cheatsheet, it will may help you to answer all your questions.
  • Reading TypeScript error can be confusing, if you need help you can copy/paste your error in ts-error-translator

πŸ‘¨β€πŸš€ Exercise 3

  • Use the shortcut tsrnfe to create/update your components and move them to ./src/components/
  • Add interface declarations for your components