Intro to TypeScript
- Strong Static Typing support
- Support for major IDEs
- Error highlighting at compile time
- Great integration with other tooling to provide hints
TypeScript is and has been continuously improved by Microsoft since 2012.
You can learn more about TypeScript from their official website.
How To Create a New React Project With TypeScript
The most common way to create a new React project is through
Create React App, which provides us with the tooling to create a new application in seconds.
The command is available for all of the significant package managers, such as
As such, all that we need to do to create a whole new TypeScript React application is to run the following command (Depending on your package manager of choice):
npx create-react-app app-name --template typescript
npm init react-app app-name --template typescript
yarn create react-app app-name --template typescript
That should give us a new empty application that would look something like this:
Adding TypeScript to an Existing React Application
Sometimes, due to various circumstances, we have to work on projects that have not yet incorporated React. That, however, shouldn’t be an issue, as the process of adding TypeScript to an already existing React project is relatively straightforward.
Let’s take the application we’ve created in the What does the useCallback hook do? article:
As you may notice from the file extensions and the
package.json file, we are not currently using TypeScript.
The way to add it to our application is to, first of all, install the following packages:
You can do that both with
npm, using the
install command, or with
yarn, using the
add command; both followed by the package(s) name(s):
In my case, it would look something like this:
By adding type support to our props and state definition statements, we can make our application more predictable and, thus, easier to work with in the future.
It might be a bit of a hassle to integrate TypeScript into a larger React project; however, the benefits will highly outweigh the integration time in the long term by making our lives easier as developers when trying to debug future issues.
While we haven’t gone into too much depth in regard to the pros/cons of adding TypeScript to our React applications, we have managed to discuss the ways how we can actually add to our projects.
There will be a follow-up article in the future regarding an in-depth overview of TypeScript, but until then, I do encourage you to check their official website, as well as this article.
I hope you’ve enjoyed the read and it helped you gain some insight into how to add TypeScript to your project and the tools required to do.
Feel free to leave any feedback on this article in the comments section below.
💬 Leave a comment