📌
My Docs
React
React
  • General Notes
    • index
    • Review-Of-Previous-Concepts
    • Reiew
    • Spread and Rest
    • Understanding By Example
    • React-Resources
    • Using Web Components in React
    • Thinking in React
    • Hello World
    • REACT ENVIORMENT
    • Components And Props
    • Composition vs Inheritance
    • JSX
    • Advanced
    • Project Examples
    • Node.js versus Next.js - A React Approach
    • Composition vs Inheritance
    • React Components
    • Docs
    • Prerequisites
      • Callbacks
      • Scope
      • Mutability
      • Array-CB-Methods
      • Objects
      • Glossary
    • index
    • Question Set #1:
    • Website
    • Editor Setup
    • Quick Start
    • JavaScript in JSX with Curly Braces
    • Your First Component
    • Reducer
    • Passing Data Deeply with Context
    • Manipulating the DOM with Refs
    • Rendering Lists
    • Choosing the State Structure
    • Tips
  • Udemy React & Redux
    • JSX
    • Modern+React+With+Redux
    • Examples
  • Articles
    • Introduction to React for Complete Beginners
    • A Comprehensive Deep Dive into React
    • Super Simple Intro To React
    • Basic React Tutorial
  • REACT DOCS
    • Shallow Compare
    • Performance Tools
    • Keyed Fragments
    • Test Utilities
    • Code-Splitting
    • Introducing Concurrent Mode (Experimental)
    • Components and Props
    • Concurrent Mode API Reference (Experimental)
    • Conditional Rendering
    • Suspense for Data Fetching (Experimental)
    • Cross-origin Errors
    • Error Decoder
    • Error Boundaries
    • New React App
    • Passing Functions to Components
    • recommended way to structure React projects?
    • Forms
    • Fragments
    • Getting Started
    • Versioning Policy
    • Add-Ons
    • Rules of Hooks
    • Using the State Hook
    • How to Contribute
    • Introducing JSX
    • JSX In Depth
    • Event Pooling
    • Portals
    • Optimizing Performance
    • React Without ES6
    • SyntheticEvent
    • PureRenderMixin
    • ReactDOMServer
    • Profiler API
    • Test Renderer
    • Refs and the DOM
    • Static Type Checking
    • State and Lifecycle
    • Uncontrolled Components
    • Web Components
    • PureRenderMixin
Powered by GitBook
On this page
  • Flow
  • TypeScript
  • ReScript
  • Kotlin
  • Other Languages

Was this helpful?

  1. REACT DOCS

Static Type Checking

PreviousRefs and the DOMNextState and Lifecycle

Last updated 3 years ago

Was this helpful?

Static type checkers like and 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 of PropTypes 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 an to learn its basics.

To use Flow, you need to:

  • Add Flow to your project as a dependency.

  • Ensure that Flow syntax is stripped from the compiled code.

  • Add type annotations and run Flow to check them.

We will explain these steps below in detail.

Adding Flow to a Project

First, navigate to your project directory in the terminal. You will need to run the following command:

If you use , run:

yarn add --dev flow-bin

If you use , run:

npm install --save-dev flow-bin

This command installs the latest version of Flow into your project.

Now, add flow to the "scripts" section of your package.json to be able to use this from the terminal:

{
  // ...
  "scripts": {
    "flow": "flow",
    // ...
  },
  // ...
}

Finally, run one of the following commands:

yarn run flow init
npm run flow init

This command will create a Flow configuration file that you will need to commit.

Stripping Flow Syntax from the Compiled Code

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.

Create React App

Babel

Note:

These instructions are not 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 you don'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:

yarn add --dev @babel/preset-flow

If you use npm, run:

npm install --save-dev @babel/preset-flow
{
  "presets": [
    "@babel/preset-flow",
    "react"
  ]
}

This will let you use the Flow syntax in your code.

Note:

Flow does not require the react preset, but they are often used together. Flow itself understands JSX syntax out of the box.

Other Build Setups

Running Flow

If you followed the instructions above, you should be able to run Flow for the first time.

yarn flow

If you use npm, run:

npm run flow

You should see a message like:

No errors!
✨  Done in 0.17s.

Adding Flow Type Annotations

By default, Flow only checks the files that include this annotation:

// @flow

Typically it is placed at the top of a file. Try adding it to some files in your project and run yarn flow or npm run flow to see if Flow already found any issues.

Now you're all set! We recommend to check out the following resources to learn more about Flow:

TypeScript

To use TypeScript, you need to:

  • Add TypeScript as a dependency to your project

  • Configure the TypeScript compiler options

  • Use the right file extensions

  • Add definitions for libraries you use

Let's go over these in detail.

Using TypeScript with Create React App

Create React App supports TypeScript out of the box.

To create a new project with TypeScript support, run:

npx create-react-app my-app --template typescript

Note:

If you use Create React App, you can skip the rest of this page. It describes the manual setup which doesn't apply to Create React App users.

Adding TypeScript to a Project

It all begins with running one command in your terminal.

yarn add --dev typescript
npm install --save-dev typescript

Congrats! You've installed the latest version of TypeScript into your project. Installing TypeScript gives us access to the tsc command. Before configuration, let's add tsc to the "scripts" section in our package.json:

{
  // ...
  "scripts": {
    "build": "tsc",
    // ...
  },
  // ...
}

Configuring the TypeScript Compiler

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 called tsconfig.json. To generate this file:

yarn run tsc --init
npx tsc --init

Of the many options, we'll look at rootDir and outDir. 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:

  • Firstly, let's arrange our project structure like this. We'll place all our source code in the src directory.

├── package.json
├── src
│   └── index.ts
└── tsconfig.json
  • Next, we'll tell the compiler where our source code is and where the output should go.

// tsconfig.json

{
  "compilerOptions": {
    // ...
    "rootDir": "src",
    "outDir": "build"
    // ...
  },
}

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.

File extensions

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 contain JSX.

Running TypeScript

If you followed the instructions above, you should be able to run TypeScript for the first time.

yarn build

If you use npm, run:

npm run build

If you see no output, it means that it completed successfully.

Type Definitions

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 an index.d.ts file in the project. Some libraries will have it specified in their package.json under the typings or types field.

# yarn
yarn add --dev @types/react

# npm
npm i --save-dev @types/react

Local Declarations Sometimes 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 a declarations.d.ts file in the root of your source directory. A simple declaration could look like this:

declare module 'querystring' {
  export function stringify(val: object): string
  export function parse(val: string): object
}

You are now ready to code! We recommend to check out the following resources to learn more about TypeScript:

ReScript

Kotlin

Other Languages

If you use , run:

If you use , run:

If your project was set up using , congratulations! The Flow annotations are already being stripped by default so you don't need to do anything else in this step.

Then add the flow preset to your . For example, if you configure Babel through .babelrc file, it could look like this:

If you don't use either Create React App or Babel, you can use to strip the type annotations.

There is also to force Flow to check all 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.

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 React .

You can also add it to an existing Create React App project, .

If you use , run:

If you use , run:

If you use , run:

If you use , run:

Looking at the now generated tsconfig.json, you can see that there are many options you can use to configure the compiler. For a detailed description of all the options, check .

Great! Now when we run our build script the compiler will output the generated javascript to the build folder. The provides a tsconfig.json with a good set of rules to get you started.

- 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.

is a typed language that compiles to JavaScript. Some of its core features are guaranteed 100% type coverage, first-class JSX support and to allow integration in existing JS / TS React codebases.

You can find more infos on integrating ReScript in your existing JS / React codebase .

is a statically typed language developed by JetBrains. Its target platforms include the JVM, Android, LLVM, and .

JetBrains develops and maintains several tools specifically for the React community: as well as . 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, with . Check out their respective sites for more information, and feel free to add more statically typed languages that work with React to this page!

Flow
TypeScript
Flow
introduction to Flow
Yarn
npm
Yarn
npm
Create React App
Babel configuration
flow-remove-types
an option
Flow Documentation: Type Annotations
Flow Documentation: Editors
Flow Documentation: React
Linting in Flow
TypeScript
here
as documented here
Yarn
npm
Yarn
npm
here
TypeScript React Starter
DefinitelyTyped
TypeScript Documentation: Everyday Types
TypeScript Documentation: Migrating from JavaScript
TypeScript Documentation: React and Webpack
ReScript
dedicated React bindings
here
Kotlin
JavaScript
React bindings
Create React Kotlin App
F#/Fable
elmish-react