TypeScript + React

Catheryne Small
Popmenu Engineering
2 min readDec 21, 2022

What I learned at CONNECT.TECH 2022

Photo by Ryland Dean on Unsplash

This year I was able to attend my first tech conference and here is what I learned during one of the sessions.

As someone with little experience with TypeScript, I thought Ben Ilegbodu gave a great talk on using TypeScript with React. But before we dive into the juicy details what is TypeScript in the first place?

TypeScript is a static type-checker, which means that you’re able to describe the shapes and behaviors of values used in your program. Because of this, catching errors and bugs during build time is more likely.

How can we use it with React?

We can use TypeScript to define props used in React function components.

interface AppProps {
// define props and types
}

const App = (props: AppProps) => {
// use props and render UI
}

Because TypeScript is being used the props must be defined in the interface/type to avoid errors being thrown. In the example below the component is trying to pass two props called name and message. What error do you expect based on the defined props?

interface AppProps {
name: string;
}

<App name="Catty" message="Learns TypeScript" />

If you said the error would tell us that message does not exist on type AppProps, you’re correct. See you’re getting it 👍. Props must be defined/listed to be used.

Props are also required by default. This means whatever values are defined in the type must be passed to the component. With that in mind the example below should throw an error about the message property being missing but required.

interface AppProps {
names: string[];
message: string;
}

<App names={['Catty', 'Tonia', 'Matthew']} />

It’s really simple to make the props optional. You add a question mark (?) in front of the colon (:). See below.

interface AppProps {
names: string[];
message?: string;
}

Because the props are required and have to be defined, refactoring bugs are easier to catch as well. Let’s say you are refactoring a component and change a prop name, datatype, or remove it and forget to edit the interface/type. An error will be thrown notifying you.

TypeScript and React hooks work together.

const App = () => {
const [user, setUser] = useState<User | null>(null)

useEffect(() => {
getUserApi().then((data) => { setUser(data.user) })
}, [])

return user ? <User user={user} /> : null
}

The syntax useHook<type>(arg) is called TypeScript Generics. That’s a whole other topic for another article. See these two resources (1|2) in the meantime. I encourage you to look at this site to see more examples of using hooks like useEffect, custom hooks, and useRef.

Welcome to the end. Overall I think TypeScript is interesting and can be a game changer, but it’s not the answer to everything. Make sure you’re still out there writing tests for your code.

--

--