Implementing TypeScript With React

Implementing TypeScript With React

ยท

3 min read

This article with cover implementing TypeScript with React. We will talk about where to use types, how to implement types with state, prop types and more.

Lets get right into it!

Creating A React App With TypeScript

To create a react app with TypeScript, we can use create-react-app with the --typescript flag. This will bootstrap a react application with TypeScript.

Using NPM:

npx create-react-app --typescript example-app

Using Yarn:

yarn create react-app --typescript example-app

Change 'example-app' to the name of your application

Once your application is setup, you will notice all js files have a .ts extension because they are now TypeScript files.

Functional Components

When creating a functional component, we can use the FC type exported by react to give the function a functional component type.

This would look like this:

const App: FC = () => {
    return <div>
        <h1>App</h1>
    </div>
}

We can also define types for props by passing in a type to FC like this:

const App: FC<IProps> = (props) => {
    return <div>
        <h1>App</h1>
    </div>
}

IProps would be a type or interface with the types of all props the component receives

Alternatively, we can define the prop types like we would a regular parameter of a function:

const App: FC = (props: IProps) => {
    return <div>
        <h1>App</h1>
    </div>
}

This would work the exact same way.

Using useState

When using useState, we can define the type of the state by passing it in <> after the declaration.

This would look like this:

const [name, setName] = useState<string>("Blake");

The specifying the type in this case is unnecessary since it can be directly inferred from the string. It would be necessary to define the type if it may change when the value is changed.

Some Other Types

Some other types you may want to know include:

  • HTMLInputElement - for html inputs
  • React.ChangeEvent - for input change events
  • React.FormEvent - for form submissions

There are obviously plenty of types out there related to react as you build applications and implement new features you will likely run into type errors which you can solve by simply searching up the error and finding the type needed for the situation.

Take Away

In this article, we have covered how to implement TypeScript with React and some common types you will often need. I hope you've learned something useful and can start using TypeScript in your React applications.

๐Ÿ‘Œ Thanks for reading this article!

If you like what I do and would love to see more related content, follow me on my other social platforms:

Github: Blake-K-Yeboah

LinkedIn: Blake Yeboah

You can also show your support by buying me a coffee ๐Ÿ˜ƒ

ย