PRO Egghead course on TypeScript and React

Setup

Our browser quickstart already sets you up to develop react applications. Here are the key highlights.

  • 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:

  1. declare module JSX {
  2. interface IntrinsicElements {
  3. a: React.HTMLAttributes;
  4. abbr: React.HTMLAttributes;
  5. div: React.HTMLAttributes;
  6. span: React.HTMLAttributes;
  7. /// so on ...
  8. }
  9. }

Stateless Functional Components

You can define stateless components simply with the React.SFC interface e.g.

  1. type Props = {
  2. foo: string;
  3. }
  4. const MyComponent: React.SFC<Props> = (props) => {
  5. return <span>{props.foo}</span>
  6. }
  7. <MyComponent foo="bar" />

Stateful Components

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:

  1. type Props = {
  2. foo: string;
  3. }
  4. class MyComponent extends React.Component<Props, {}> {
  5. render() {
  6. return <span>{this.props.foo}</span>
  7. }
  8. }
  9. <MyComponent foo="bar" />

React JSX Tip: Interface for renderable

React can render a few things like JSX or string. There are all consolidated into the type React.ReactNode so use it for when you want to accept renderables e.g.

  1. type Props = {
  2. header: React.ReactNode;
  3. body: React.ReactNode;
  4. }
  5. class MyComponent extends React.Component<Props, {}> {
  6. render() {
  7. return <div>
  8. {this.props.header}
  9. {this.props.body}
  10. </div>;
  11. }
  12. }
  13. <MyComponent foo="bar" />

React JSX Tip: Accept an instance of a Component

The react type definitions provide React.ReactElement<T> to allow you to annotate the result of a <T/> class component instantiation. e.g.

  1. class MyAwesomeComponent extends React.Component {
  2. render() {
  3. return <div>Hello</div>;
  4. }
  5. }
  6. const foo: React.ReactElement<MyAwesomeComponent> = <MyAwesomeComponent />; // Okay
  7. const bar: React.ReactElement<MyAwesomeComponent> = <NotMyAwesomeComponent />; // Error!

Of course you can use this as a function argument annotation and even React component prop member.

React JSX Tip: Generic components

It works exactly as expected. Here is an example:

  1. /** A generic component */
  2. type SelectProps<T> = { items: T[] }
  3. class Select<T> extends React.Component<SelectProps<T>, any> { }
  4. /** Usage */
  5. const Form = () => <Select<string> items={['a','b']} />;

Generic functions

Something like the following works fine:

  1. function foo<T>(x: T): T { return x; }

However using an arrow generic function will not:

  1. const foo = <T>(x: T) => x; // ERROR : unclosed `T` tag

Workaround: Use extends on the generic parameter to hint the compiler that it’s a generic, e.g.:

  1. const foo = <T extends {}>(x: T) => x;

Type Assertions

Use as Foo syntax for type assertions as we mentioned before.

Default Props

  • 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).
  1. class Hello extends React.Component<{
  2. /**
  3. * @default 'TypeScript'
  4. */
  5. compiler?: string,
  6. framework: string
  7. }> {
  8. static defaultProps = {
  9. compiler: 'TypeScript'
  10. }
  11. render() {
  12. const compiler = this.props.compiler!;
  13. return (
  14. <div>
  15. <div>{compiler}</div>
  16. <div>{this.props.framework}</div>
  17. </div>
  18. );
  19. }
  20. }
  21. ReactDOM.render(
  22. <Hello framework="React" />, // TypeScript React
  23. document.getElementById("root")
  24. );
  • SFC with default props: Recommend leveraging simple JavaScript patterns as they work well with TypeScript’s type system e.g.
  1. const Hello: React.SFC<{
  2. /**
  3. * @default 'TypeScript'
  4. */
  5. compiler?: string,
  6. framework: string
  7. }> = ({
  8. compiler = 'TypeScript', // Default prop
  9. framework
  10. }) => {
  11. return (
  12. <div>
  13. <div>{compiler}</div>
  14. <div>{framework}</div>
  15. </div>
  16. );
  17. };
  18. ReactDOM.render(
  19. <Hello framework="React" />, // TypeScript React
  20. document.getElementById("root")
  21. );