Why TypeScript?
I have another article that explains a lot about TypeScript, what it is and how and why you should use it.
You're welcome to read about it here: https://dev.to/omerwow/how-i-began-using-typescript-3noe
In a nutshell, the benefits of using TypeScript include:
- Catching errors early in the development process.
- Making code easier to understand and maintain.
- Providing a better development experience, with features like autocompletion and type checking.
Getting started
To create a new React application with TypeScript, use the following command:
npx create-react-app my-app --template typescript
That's it, the Create React App CLI will create a new app with TypeScript configured properly and you can get started right away.
If, however, you have an existing React app that you want to convert to TypeScript, you're going to need to do a few extra steps.
Don't worry though, it's pretty simple!
First, install TypeScript and other required packages:
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
Now, rename all .js files to .tsx files, and make sure to restart your dev server before continuing.
Also, a restart to your code editor / IDE may be needed or helpful as well.
The last thing you're going to need to do is to create a tsconfig.json file.
This file will usually be created for you when creating a new project, but since this an existing project, you're going to need to create it yourself.
In the root folder of your project, just create a new file called tsconfig.json, and paste the following inside it:
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}
That's pretty much it.
Be aware that enabling TypeScript in an existing project can "introduce" or uncover some errors.
This is usually not a big deal and may even be pretty helpful and help you solve a few bugs. You're going to need to deal with them before continuing development.
Now that we have a working TypeScript React app, we can start utilizing TypeScript to improve our development.
Writing .tsx files
We'll start with a simple React component that renders a header. Then we'll use TypeScript to add types and type safety to the component. Finally, we'll compile the TypeScript code to JavaScript and run the app.
First, let's create a simple React component that renders a header:
import React from 'react';
const Header = () => {
return (
<header>
<h1>Hello, world!</h1>
</header>
);
};
export default Header;
This Header component doesn't do much yet it just renders a header element with the text "Hello, world!" We can write this component in TypeScript or JavaScript. For this example, we'll write it in TypeScript.
Adding Types with TypeScript
Now that we have a basic React component, let's add some types with TypeScript. We can start by adding types to our props and state:
import React from 'react';
interface HeaderProps {
message: string;
}
const Header = (props: HeaderProps) => {
return (
<header>
<h1>{props.message}</h1>
</header>
);
};
export default Header;
As you can see, we've added an interface for our props and specified that the message prop is of type string. This way, if we try to pass anything other than a string to the message prop, TypeScript will give us an error.
We can also add types to our state:
import React, { useState } from 'react';
const [count, setCount] = useState<number>(0);
const Header = (props: HeaderProps) => {
return (
<header>
<h1>{props.message}</h1>
<button onClick={() => setCount(count + 1)}>
Click me!
</button>
<p>You've clicked the button {count} times.</p>
</header>
);
};
export default Header;
As you can see, we've added types for our state and specified that the count state variable is of type number. This way, if we try to set the count state variable to anything other than a number, TypeScript will give us an error.
Exploring the type safety of React event handlers
One of the benefits of using TypeScript with React is that developers can catch errors in their event handlers. Event handlers are a way to respond to user input in React applications. When an event occurs, such as a user clicking a button, The compiler will check the type of each parameter in the event handler function, and it will also check the return type of the function. If there is a mismatch in either of them, the compiler will throw an error. This means that developers can catch errors in their event handlers before the code runs.
However, there are some potential pitfalls when using TypeScript with React. One pitfall is that it is possible to write code that is valid TypeScript but will not compile because of an error in React. For example, take a look at the following code:
class MyComponent extends React.Component {
handleClick(event: MouseEvent) {
// do something
}
}
This code will not compile because of an error in React: "handleClick" must be declared as a static method on "MyComponent". However, this code is valid TypeScript, and it will only produce an error when it is compiled with React. This means that developers need to be aware of both TypeScript and React when they are writing their code.
In conclusion, TypeScript is a great way to improve your React code. It can help you catch errors, optimize performance, and make your code more readable. Plus, it's just plain fun to use.
Star our Github repo and join the discussion in our Discord channel!
Test your API for free now at BLST!