These docs are old and won’t be updated. Go toreact.dev for the new React docs.
Check outReact TypeScript cheatsheet for how to use React with TypeScript.
Static type checkers likeFlow andTypeScript identify certain types of problems before you even run your code. They can also improve developer workflow by adding features like auto-completion. For this reason, we recommend using Flow or TypeScript instead ofPropTypes for larger code bases.
Flow is a static type checker for your JavaScript code. It is developed at Facebook and is often used with React. It lets you annotate the variables, functions, and React components with a special type syntax, and catch mistakes early. You can read anintroduction to Flow to learn its basics.
To use Flow, you need to:
We will explain these steps below in detail.
First, navigate to your project directory in the terminal. You will need to run the following command:
If you useYarn, run:
yarnadd--dev flow-binIf you usenpm, run:
npminstall --save-dev flow-binThis command installs the latest version of Flow into your project.
Now, addflow to the"scripts" section of yourpackage.json to be able to use this from the terminal:
{// ..."scripts":{"flow":"flow",// ...},// ...}Finally, run one of the following commands:
If you useYarn, run:
yarn run flow initIf you usenpm, run:
npm run flow initThis command will create a Flow configuration file that you will need to commit.
Flow extends the JavaScript language with a special syntax for type annotations. However, browsers aren’t aware of this syntax, so we need to make sure it doesn’t end up in the compiled JavaScript bundle that is sent to the browser.
The exact way to do this depends on the tools you use to compile JavaScript.
If your project was set up usingCreate React App, congratulations! The Flow annotations are already being stripped by default so you don’t need to do anything else in this step.
Note:
These instructions arenot for Create React App users. Even though Create React App uses Babel under the hood, it is already configured to understand Flow. Only follow this step if youdon’t use Create React App.
If you manually configured Babel for your project, you will need to install a special preset for Flow.
If you use Yarn, run:
yarnadd--dev @babel/preset-flowIf you use npm, run:
npminstall --save-dev @babel/preset-flowThen add theflow preset to yourBabel configuration. For example, if you configure Babel through.babelrc file, it could look like this:
{"presets":["@babel/preset-flow","react"]}This will let you use the Flow syntax in your code.
Note:
Flow does not require the
reactpreset, but they are often used together. Flow itself understands JSX syntax out of the box.
If you don’t use either Create React App or Babel, you can useflow-remove-types to strip the type annotations.
If you followed the instructions above, you should be able to run Flow for the first time.
yarn flowIf you use npm, run:
npm run flowYou should see a message like:
No errors!✨ Done in 0.17s.By default, Flow only checks the files that include this annotation:
// @flowTypically it is placed at the top of a file. Try adding it to some files in your project and runyarn flow ornpm run flow to see if Flow already found any issues.
There is alsoan option to force Flow to checkall files regardless of the annotation. This can be too noisy for existing projects, but is reasonable for a new project if you want to fully type it with Flow.
Now you’re all set! We recommend to check out the following resources to learn more about Flow:
TypeScript is a programming language developed by Microsoft. It is a typed superset of JavaScript, and includes its own compiler. Being a typed language, TypeScript can catch errors and bugs at build time, long before your app goes live. You can learn more about using TypeScript with Reacthere.
To use TypeScript, you need to:
Let’s go over these in detail.
Create React App supports TypeScript out of the box.
To create anew project with TypeScript support, run:
npx create-react-app my-app--template typescriptYou can also add it to anexisting Create React App project,as documented here.
Note:
If you use Create React App, you canskip the rest of this page. It describes the manual setup which doesn’t apply to Create React App users.
It all begins with running one command in your terminal.
If you useYarn, run:
yarnadd--dev typescriptIf you usenpm, run:
npminstall --save-dev typescriptCongrats! You’ve installed the latest version of TypeScript into your project. Installing TypeScript gives us access to thetsc command. Before configuration, let’s addtsc to the “scripts” section in ourpackage.json:
{// ..."scripts":{"build":"tsc",// ...},// ...}The compiler is of no help to us until we tell it what to do. In TypeScript, these rules are defined in a special file calledtsconfig.json. To generate this file:
If you useYarn, run:
yarn run tsc--initIf you usenpm, run:
npx tsc--initLooking at the now generatedtsconfig.json, you can see that there are many options you can use to configure the compiler. For a detailed description of all the options, checkhere.
Of the many options, we’ll look atrootDir andoutDir. In its true fashion, the compiler will take in typescript files and generate javascript files. However we don’t want to get confused with our source files and the generated output.
We’ll address this in two steps:
src directory.├── package.json├── src│ └── index.ts└── tsconfig.json// tsconfig.json{"compilerOptions":{// ..."rootDir":"src","outDir":"build"// ...},}Great! Now when we run our build script the compiler will output the generated javascript to thebuild folder. TheTypeScript React Starter provides atsconfig.json with a good set of rules to get you started.
Generally, you don’t want to keep the generated javascript in your source control, so be sure to add the build folder to your.gitignore.
In React, you most likely write your components in a.js file. In TypeScript we have 2 file extensions:
.ts is the default file extension while.tsx is a special extension used for files which containJSX.
If you followed the instructions above, you should be able to run TypeScript for the first time.
yarn buildIf you use npm, run:
npm run buildIf you see no output, it means that it completed successfully.
To be able to show errors and hints from other packages, the compiler relies on declaration files. A declaration file provides all the type information about a library. This enables us to use javascript libraries like those on npm in our project.
There are two main ways to get declarations for a library:
Bundled - The library bundles its own declaration file. This is great for us, since all we need to do is install the library, and we can use it right away. To check if a library has bundled types, look for anindex.d.ts file in the project. Some libraries will have it specified in theirpackage.json under thetypings ortypes field.
DefinitelyTyped - DefinitelyTyped is a huge repository of declarations for libraries that don’t bundle a declaration file. The declarations are crowd-sourced and managed by Microsoft and open source contributors. React for example doesn’t bundle its own declaration file. Instead we can get it from DefinitelyTyped. To do so enter this command in your terminal.
# yarnyarnadd--dev @types/react# npmnpm i --save-dev @types/reactLocal DeclarationsSometimes the package that you want to use doesn’t bundle declarations nor is it available on DefinitelyTyped. In that case, we can have a local declaration file. To do this, create adeclarations.d.ts file in the root of your source directory. A simple declaration could look like this:
declaremodule'querystring'{exportfunctionstringify(val: object):stringexportfunctionparse(val:string): object}You are now ready to code! We recommend to check out the following resources to learn more about TypeScript:
ReScript is a typed language that compiles to JavaScript. Some of its core features are guaranteed 100% type coverage, first-class JSX support anddedicated React bindings to allow integration in existing JS / TS React codebases.
You can find more infos on integrating ReScript in your existing JS / React codebasehere.
Kotlin is a statically typed language developed by JetBrains. Its target platforms include the JVM, Android, LLVM, andJavaScript.
JetBrains develops and maintains several tools specifically for the React community:React bindings as well asCreate React Kotlin App. The latter helps you start building React apps with Kotlin with no build configuration.
Note there are other statically typed languages that compile to JavaScript and are thus React compatible. For example,F#/Fable withelmish-react. Check out their respective sites for more information, and feel free to add more statically typed languages that work with React to this page!