How do I use TypeScript with React?
Posted on January 11, 2020  (Last modified on November 9, 2022 )
2 minutes • 320 words
But how do you do that? There are two different ways.
Using the –typescript flag with create-react-app
If you’re starting a new React project, the easiest way to enable typescript is via a flag to create-react-app when starting your new react project. If you’re not starting your react project with create-react-app (you probably should !) then this section won’t apply to you.
create-react-app ships with a number of flags that can be listed by running
create-react-app --help in your terminal. The one we want to use is the
--typescript flag, and we can use it like so:
create-react-app frontend --typescript
This creates a new React app in our current directory named “frontend” and initializes it with typescript support. You can now open this in your editor and where you would see
.js files, you’ll now see
.ts files. Your build pipeline is already configured, so you’re good to start coding right away!
, this is as simple as adding a new loader (like awesome-typescript-loader
create-react-app, run the above command, and immediately
npm run eject. This will eject a webpack config already configured for use with TypeScript. Then you can copy the relevant pieces into your own config.