JSX | Typescript

Basic usage#

In order to use JSX you must do two things.

  1. Name your files with a .tsx extension
  2. Enable the jsx option

TypeScript ships with three JSX modes: preserve, react, and react-native.

These modes only affect the emit stage - type checking is unaffected.

The preserve mode will keep the JSX as part of the output to be further consumed by another transform step (e.g. Babel). Additionally the output will have a .jsx file extension.

The react mode will emit React.createElement, does not need to go through a JSX transformation before use, and the output will have a .js file extension.

The react-native mode is the equivalent of preserve in that it keeps all JSX, but the output will instead have a .js file extension.

ModeInputOutputOutput File Extension
preserve<div /><div />.jsx
react<div />React.createElement("div").js
react-native<div /><div />.js

You can specify this mode using either the --jsx command line flag or the corresponding option in your tsconfig.json file.

*Note: You can specify the JSX factory function to use when targeting react JSX emit with --jsxFactory option (defaults to React.createElement)

The as operator#

// TypeScript disallows angle bracket type assertions in .tsx files
var foo = <foo>bar;
var foo = bar as foo;

Type Checking#

Intrinsic elements#

Intrinsic elements are looked up on the special interface JSX.IntrinsicElements.

By default, if this interface is not specified, then anything goes and intrinsic elements will not be type checked.

However, if this interface is present, then the name of the intrinsic element is looked up as a property on the JSX.IntrinsicElements interface.

declare namespace JSX {
interface IntrinsicElements {
foo: any
}
}
<foo />; // ok
<bar />; // error

Note: You can also specify a catch-all string indexer on JSX.IntrinsicElements as follows:

declare namespace JSX {
interface IntrinsicElements {
[elemName: string]: any;
}
}

Value-based elements#

Value-based elements are simply looked up by identifiers that are in scope.

import MyComponent from "./myComponent";
<MyComponent />; // ok
<SomeOtherComponent />; // error

There are two ways to define a value-based element:

  1. Function Component (FC)
  2. Class Component

Because these two types of value-based elements are indistinguishable from each other in a JSX expression, first TS tries to resolve the expression as a Function Component using overload resolution. If the process succeeds, then TS finishes resolving the expression to its declaration. If the value fails to resolve as a Function Component, TS will then try to resolve it as a class component. If that fails, TS will report an error.

Function Component#

As the name suggests, the component is defined as a JavaScript function where its first argument is a props object.

TS enforces that its return type must be assignable to JSX.Element.

interface FooProp {
name: string;
X: number;
Y: number;
}
declare function AnotherComponent(prop: {name: string});
function ComponentFoo(prop: FooProp) {
return <AnotherComponent name={prop.name} />;
}
const Button = (prop: {value: string}, context: { color: string }) => <button>

Function overloads:

interface ClickableProps {
children: JSX.Element[] | JSX.Element
}
interface HomeProps extends ClickableProps {
home: JSX.Element;
}
interface SideProps extends ClickableProps {
side: JSX.Element | string;
}
function MainButton(prop: HomeProps): JSX.Element;
function MainButton(prop: SideProps): JSX.Element {
...
}

Class Component#

It is possible to define the type of a class component. However, to do so it is best to understand two new terms: the element class type and the element instance type.

Given <Expr />, the element class type is the type of Expr. So in the example above, if MyComponent was an ES6 class the class type would be that class's constructor and statics. If MyComponent was a factory function, the class type would be that function.

Once the class type is established, the instance type is determined by the union of the return types of the class type's construct or call signatures (whichever is present).

class MyComponent {
render() {}
}
// use a construct signature
var myComponent = new MyComponent();
// element class type => MyComponent
// element instance type => { render: () => void }
function MyFactoryFunction() {
return {
render: () => {
}
}
}
// use a call signature
var myComponent = MyFactoryFunction();
// element class type => MyFactoryFunction
// element instance type => { render: () => void }

The element instance type is interesting because it must be assignable to JSX.ElementClass or it will result in an error. By default JSX.ElementClass is {}, but it can be augmented to limit the use of JSX to only those types that conform to the proper interface.

declare namespace JSX {
interface ElementClass {
render: any;
}
}
class MyComponent {
render() {}
}
function MyFactoryFunction() {
return { render: () => {} }
}
<MyComponent />; // ok
<MyFactoryFunction />; // ok
class NotAValidComponent {}
function NotAValidFactoryFunction() {
return {};
}
<NotAValidComponent />; // error
<NotAValidFactoryFunction />; // error

Attribute type checking#

For intrinsic elements, it is the type of the property on JSX.IntrinsicElements

declare namespace JSX {
interface IntrinsicElements {
foo: { bar?: boolean }
}
}
// element attributes type for 'foo' is '{bar?: boolean}'
<foo bar />;

Note: If an attribute name is not a valid JS identifier (like a data-* attribute), it is not considered to be an error if it is not found in the element attributes type.

For value-based elements, it is a bit more complex. It is determined by the type of a property on the element instance type that was previously determined. Which property to use is determined by JSX.ElementAttributesProperty.

declare namespace JSX {
interface ElementAttributesProperty {
props; // specify the property name to use
}
}
class MyComponent {
// specify the property on the element instance type
props: {
foo?: string;
}
}
// element attributes type for 'MyComponent' is '{foo?: string}'
<MyComponent foo="bar" />

Children Type Checking#

Similar to how TS uses JSX.ElementAttributesProperty to determine the name of props, TS uses JSX.ElementChildrenAttribute to determine the name of children within those props.

JSX.ElementChildrenAttribute should be declared with a single property.

declare namespace JSX {
interface ElementChildrenAttribute {
children: {}; // specify children name to use
}
}
<div>
<h1>Hello</h1>
</div>;
<div>
<h1>Hello</h1>
World
</div>;
const CustomComp = (props) => <div>{props.children}</div>
<CustomComp>
<div>Hello World</div>
{"This is just a JS expression..." + 1000}
</CustomComp>

You can specify the type of children like any other attribute. This will override the default type from, eg the React typings if you use them.

interface PropsType {
children: JSX.Element
name: string
}
class Component extends React.Component<PropsType, {}> {
render() {
return (
<h2>
{this.props.children}
</h2>
)
}
}
// OK
<Component name="foo">
<h1>Hello World</h1>
</Component>
// Error: children is of type JSX.Element not array of JSX.Element
<Component name="bar">
<h1>Hello World</h1>
<h2>Hello World</h2>
</Component>
// Error: children is of type JSX.Element not array of JSX.Element or string.
<Component name="baz">
<h1>Hello</h1>
World
</Component>

React integration#

To use JSX with React you should use the React typings. These typings define the JSX namespace appropriately for use with React.

/// <reference path="react.d.ts" />
interface Props {
foo: string;
}
class MyComponent extends React.Component<Props, {}> {
render() {
return <span>{this.props.foo}</span>
}
}
<MyComponent foo="bar" />; // ok
<MyComponent foo={0} />; // error

Factory Functions#

The exact factory function used by the jsx: react compiler option is configurable. It may be set using either the jsxFactory command line option, or an inline @jsx comment pragma to set it on a per-file basis. For example, if you set jsxFactory to createElement, <div /> will emit as createElement("div") instead of React.createElement("div").

The comment pragma version may be used like so (in TypeScript 2.8):

import preact = require("preact");
/* @jsx preact.h */
const x = <div />;

emits as:

const preact = require("preact");
const x = preact.h("div", null);

The factory chosen will also affect where the JSX namespace is looked up (for type checking information) before falling back to the global one. If the factory is defined as React.createElement (the default), the compiler will check for React.JSX before checking for a global JSX. If the factory is defined as h, it will check for h.JSX before a global JSX.