Stefan Baumgartner

TypeScript and React: Getting Started

TypeScript is a natural fit for React, not only because TypeScript is a full fledged JSX compiler. Which means
that you don’t need a huge building setup. TypeScript includes everything you need. One thing you might want is a
bundling tool. Parcel is one choice with easy to no configuration, but you can also use
Webpack.

The TypeScript docs have some documentation on
React and Webpack and might be a good start.

tsconfig.json compiler options

To make React work smooth and nicely with TypeScript, we need to set a couple of compiler options. Here are the
most important ones:

jsx and jsxFactory

{"compilerOptions":{..."jsx":"react",...}

Other values for this are react-native if you work with React Native, and preserve, if you want to
keep JSX as it is. preserve makes sense if you want to compile it later with Babel or a predefined setup.
If you want to use TypeScript and JSX with libraries like Preact, Vue or Dojo (they all speak JSX!), you can
define a specific JSX factory:

{"compilerOptions":{..."jsx":"react","jsxFactory":"h",...}

This uses the respective virtual DOM implementation of said libraries (h) instead of React.createElement.

Synthetic default imports

TypeScript supports the ES module notation. You can import React with

import*asReactfrom'react'

but writing

importReactfrom'react'

is a wee bit nicer. Mostly because you can import type definitions and React features in a destructured way:

importReact{Component,FunctionComponent}from'react'

To make this work, we need to set both allowSyntheticDefaultImports and esModuleInterop to true:

Libraries

We use React for client-side development. That’s why we need to import some libraries to support this.
In our case, we import ES 2015 (good baseline ES features) and DOM. With DOM, we get type definitions for
things like Events, HTML nodes, …

{"compilerOptions":{..."lib":["dom","es2015"],...}

Decorators

Decorators are an experimental language feature that was added to TypeScript back when
Angular switched from their own programming language to TypeScript. Since then they have
become hugely popular, leading to tons of discussions at TC39 how to include them best
into the JavaScript language.

Since they are still at stage-2, TypeScript only features them if you turn on a flag.
Heads up: You don’t need it for your usual React tasks. Once you start using tools like
MobX, though, they might come in handy.

{"compilerOptions":{..."experimentalDecorators":true,...}

Bottom line

A ton to set up… I suggest getting the official starter package on Github.
If you have an existing setup, the infos above will help you getting everything right. Let’s start with some real code.