TypeScript + React

A short introduction

Build System

Integrates nicely with existing Webpack projects

Chain the TypeScript loader

{
    test: /\.tsx$/,
    loaders: envDep(
        ['react-hot', 'babel-loader', 'ts-loader'],
        ['babel-loader', 'ts-loader']
    ),
    include: src_dir
}

Specify the TypeScript config tsconfig.json

{
    "compilerOptions": {
        "jsx": "preserve",
        "target": "es6",
        "sourceMap": true
    },
    "files": [
        "App.tsx"
    ],
}

Advantages

React.Component requires an interface for props and state

class Button extends React.Component<IButtonProps, IButtonState> {
}

Checks the type of the props provided in JSX code

<Button text="Click me"/>

interface IButtonProps {
    text: string
}

Checks the type of the state object passed to setState

setState({
    checked: "true" // ERROR, expecting a boolean
});

interface ICheckBoxState {
    checked: boolean
}

TypeScript compiler supports JSX since v. 1.6 (September 2015)

Prefer composition

What to use:

  • interfaces for props and state are a must
  • user interfaces as much as possible
  • use types as much as possible
  • use generics
  • use enums

 

Don't go crazy with the inheritance:

  • all components should only extend React.Component
  • don't use abstract classes

TypeScript + React Intro

By kenjiru

TypeScript + React Intro

Super short introduction.

  • 482