Your Reference Guide to Using TypeScript in React

Your Reference Guide to Using TypeScript in React

Here's a quick reference guide where you can learn about best practices and generic TypeScript types in React. TypeScript supports JSX and can correctly model the patterns used in React codebases like useState

One of the issues with JavaScript is its dynamically-typed nature, meaning that data and variable types are unknown until runtime. This can have many side effects. For example, it can cause confusion within your codebase due to the fact that a variable can be anything.

To solve this issue, Microsoft released TypeScript. Anders Hejlsberg, lead architect of TypeScript, said, “What if we could strengthen JavaScript with the things that are missing for large scale application development, like static typing, classes [and] modules…? That’s what TypeScript is about.”

TypeScript instantly became the most widely used static-typed version of JavaScript. It enabled JavaScript devs to statically type data and variables. Soon enough, it was introduced to React.js, enabling React devs to write their React app in TypeScript.

But this comes at a cost: TypeScript typings and syntaxes can be difficult to keep up with, especially when used with React.

React has many features, such as props, class components, function components, function params, components lifecycle hooks, and member properties. Because typing these within TypeScript isn’t easy, this article aims to serve as a quick reference and learning guide for both beginner and advanced React devs.

With it, you’ll be able to quickly look up best practices and generic TS types in React. Ready? Let’s get started.

TypeScript typings

TypeScript has a typings folder where it saves files with *.d.ts extension. These files include interfaces that infer what shape a value will take. This is what enables TypeScript to bring data-typing to JavaScript.

An interface describes what a value would look like:

type AppState {
    propOne: number;
    propTwo: string
}

AppState describes what the value of its data-type would look like. First, we infer it would be an object that holds properties propOne and propTwo, the former being of number type and the latter being a string type. Assigning a boolean type to propOne would cause TypeScript to throw TypeError.

When we include TypeScript in our React project, every React element has an interface that defines the shape it will take. Let’s start with function component.

Function component

Function components are normal functions that return JSX elements in React and are used to create views. Initially, they are stateless components, but with the arrival of React hooks, they can be made stateful and smart/

Defining a React function component takes the React.FunctionComponent shape:

function App: React.FunctionComponent<> {
    return (
        <>
            // ...
        </>
    )
}

We can also use the shorthand React.FC:

function App: React.FC<> {
    return (
        <>
            // ...
        </>
    )
}

React.FunctionComponent, or React.FC, describes explicitly the return type of the function component.

We can type the props definitions in the arrows <>.

type AppProps = {
    message: string;
    age: number;
};

AppProps is the interface the props passed to App will take, so we can write the App component below if it would receive props:

type AppProps {
    message: string;
    age: number;
}

function App: React.FC<AppProps>(props: AppProps) {
    return (
        <>
            // ...
        </>
    )
}

We can use ? to set optional values in the typing:

type AppProps {
    message: string;
    age?: number;
}

Now, the age property becomes optional. The App component can be rendered, omitting the age property in its props object.

We can omit the type declaration within the arrows <>.

function App<{message: string; age: number;}>({message: string; age: number;}: AppProps) {
    // ...
}

Inner functions in the functional component can be typed, like so:

function App<{message: string; age: number;}>({message: string; age: number;}: AppProps) {
    // ...

    function clickHandler (val: number) {
        // ...
    }

    return (
        <>
            <button onClick={() => clickHandler(45)}            
        </>
    )
}

typescript typescript javascript web-development developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

What is TypeScript? Why TypeScript? and Why Not TypeScript?

TypeScript extends JavaScript by adding Types. There are many great reasons to switch to TypeScript. Especially if your team uses JavaScript. There are some reasons to not use TypeScript as there are with any language or framework.

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.