Use files with the extension .tsx (instead of .ts).
Use "jsx" : "react" in your tsconfig.json's compilerOptions.
Install the definitions for JSX and React into your project : (npm i -D @types/react @types/react-dom).
Import react into your .tsx files (import * as React from "react").
HTML Tags vs. Components
React can either render HTML tags (strings) or React components (classes). The JavaScript emit for these elements is different (React.createElement('div') vs. React.createElement(MyComponent)). The way this is determined is by the case of the first letter. foo is treated as an HTML tag and Foo is treated as a component.
Type Checking
HTML Tags
An HTML Tag foo is to be of the type JSX.IntrinsicElements.foo. These types are already defined for all the major tags in a file react-jsx.d.ts which we had you install as a part of the setup. Here is a sample of the the contents of the file:
Components are type checked based on the props property of the component. This is modeled after how JSX is transformed i.e. the attributes become the props of the component.
To create React Stateful components you use ES6 classes. The react.d.ts file defines the React.Component<Props,State> class which you should extend in your own class providing your own Props and State interfaces. This is demonstrated below:
React can render a few things like JSX or string. These are all consolidated into the type React.ReactNode so use it for when you want to accept renderables e.g.
Of course you can use this as a function argument annotation and even React component prop member.
React JSX Tip: Accept a component that can act on props and be rendered using JSX
The type React.Component<Props> consolidates React.ComponentClass<P> | React.StatelessComponent<P> so you can accept something that takes type Props and renders it using JSX e.g.
const X: React.Component<Props> = foo; // from somewhere
// Render X with some props:
<X {...props}/>;
React JSX Tip: Generic components
It works exactly as expected. Here is an example:
/** A generic component */
type SelectProps<T> = { items: T[] }
class Select<T> extends React.Component<SelectProps<T>, any> { }
/** Usage */
const Form = () => <Select<string> items={['a','b']} />;
Generic functions
Something like the following works fine:
function foo<T>(x: T): T { return x; }
However, using an arrow generic function will not:
Stateful components with default props: You can tell TypeScript that a property will be provided externally (by React) by using a null assertion operator (this isn't ideal but is the simplest minimum extra code solution I could think of).