- Let your computer catch errors as you code and BEFORE you ship bugs to production
- Create documentation for your team
TypeScriptis 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.
- Watch this video about the story of
TypeScriptto understand why it's a:- language
- linter
- compiler
- documentation tool
- even Bill Gates use it
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.
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>;
}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 snippets page.
- 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
- Use the shortcut
tsrnfto create/update your components and move them to./src/components/ - Add
interfacedeclarations for your components
- Install Pretty TypeScript Errors to make errors more readable.
code --install-extension yoavbls.pretty-ts-errors
