Table of contents

Introduction

Basic Usage

The as operator

Type Checking

The JSX result type

Embedding Expressions

React integration

Factory Functions

Introduction

↥ back to top

JSX is an embeddable XML-like syntax.It is meant to be transformed into valid JavaScript, though the semantics of that transformation are implementation-specific.JSX rose to popularity with the React framework, but has since seen other implementations as well.TypeScript supports embedding, type checking, and compiling JSX directly to JavaScript.

Basic usage

↥ back to top

In order to use JSX you must do two things.

  • Name your files with a .tsx extension
  • Enable the jsx optionTypeScript 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

↥ back to top

Recall how to write a type assertion:

  1. var foo = <foo>bar;

This asserts the variable bar to have the type foo.Since TypeScript also uses angle brackets for type assertions, combining it with JSX’s syntax would introduce certain parsing difficulties. As a result, TypeScript disallows angle bracket type assertions in .tsx files.

Since the above syntax cannot be used in .tsx files, an alternate type assertion operator should be used: as.The example can easily be rewritten with the as operator.

  1. var foo = bar as foo;

The as operator is available in both .ts and .tsx files, and is identical in behavior to the angle-bracket type assertion style.

Type Checking

↥ back to top

In order to understand type checking with JSX, you must first understand the difference between intrinsic elements and value-based elements.Given a JSX expression <expr />, expr may either refer to something intrinsic to the environment (e.g. a div or span in a DOM environment) or to a custom component that you’ve created.This is important for two reasons:

  • For React, intrinsic elements are emitted as strings (React.createElement("div")), whereas a component you’ve created is not (React.createElement(MyComponent)).
  • The types of the attributes being passed in the JSX element should be looked up differently. Intrinsic element attributes should be known intrinsically whereas components will likely want to specify their own set of attributes.TypeScript uses the same convention that React does for distinguishing between these.An intrinsic element always begins with a lowercase letter, and a value-based element always begins with an uppercase letter.

Intrinsic elements

↥ back to top

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.For example:

  1. declare namespace JSX {
  2. interface IntrinsicElements {
  3. foo: any
  4. }
  5. }
  6. <foo />; // ok
  7. <bar />; // error

In the above example, <foo /> will work fine but <bar /> will result in an error since it has not been specified on JSX.IntrinsicElements.

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

  1. declare namespace JSX {
  2. interface IntrinsicElements {
  3. [elemName: string]: any;
  4. }
  5. }

Value-based elements

↥ back to top

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

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

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

  • Function Component (FC)
  • Class ComponentBecause 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

↥ back to top

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.

  1. interface FooProp {
  2. name: string;
  3. X: number;
  4. Y: number;
  5. }
  6. declare function AnotherComponent(prop: {name: string});
  7. function ComponentFoo(prop: FooProp) {
  8. return <AnotherComponent name={prop.name} />;
  9. }
  10. const Button = (prop: {value: string}, context: { color: string }) => <button>

Because a Function Component is simply a JavaScript function, function overloads may be used here as well:

  1. interface ClickableProps {
  2. children: JSX.Element[] | JSX.Element
  3. }
  4. interface HomeProps extends ClickableProps {
  5. home: JSX.Element;
  6. }
  7. interface SideProps extends ClickableProps {
  8. side: JSX.Element | string;
  9. }
  10. function MainButton(prop: HomeProps): JSX.Element;
  11. function MainButton(prop: SideProps): JSX.Element {
  12. ...
  13. }

Note: Function Components were formerly known as Stateless Function Components (SFC). As Function Components can no longer be considered stateless in recent versions of react, the type SFC and its alias StatelessComponent were deprecated.

Class Component

↥ back to top

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).So again, in the case of an ES6 class, the instance type would be the type of an instance of that class, and in the case of a factory function, it would be the type of the value returned from the function.

  1. class MyComponent {
  2. render() {}
  3. }
  4. // use a construct signature
  5. var myComponent = new MyComponent();
  6. // element class type => MyComponent
  7. // element instance type => { render: () => void }
  8. function MyFactoryFunction() {
  9. return {
  10. render: () => {
  11. }
  12. }
  13. }
  14. // use a call signature
  15. var myComponent = MyFactoryFunction();
  16. // element class type => MyFactoryFunction
  17. // 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.

  1. declare namespace JSX {
  2. interface ElementClass {
  3. render: any;
  4. }
  5. }
  6. class MyComponent {
  7. render() {}
  8. }
  9. function MyFactoryFunction() {
  10. return { render: () => {} }
  11. }
  12. <MyComponent />; // ok
  13. <MyFactoryFunction />; // ok
  14. class NotAValidComponent {}
  15. function NotAValidFactoryFunction() {
  16. return {};
  17. }
  18. <NotAValidComponent />; // error
  19. <NotAValidFactoryFunction />; // error

Attribute type checking

↥ back to top

The first step to type checking attributes is to determine the element attributes type.This is slightly different between intrinsic and value-based elements.

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

  1. declare namespace JSX {
  2. interface IntrinsicElements {
  3. foo: { bar?: boolean }
  4. }
  5. }
  6. // element attributes type for 'foo' is '{bar?: boolean}'
  7. <foo bar />;

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.It should be declared with a single property.The name of that property is then used.As of TypeScript 2.8, if JSX.ElementAttributesProperty is not provided, the type of first parameter of the class element’s constructor or Function Component’s call will be used instead.

  1. declare namespace JSX {
  2. interface ElementAttributesProperty {
  3. props; // specify the property name to use
  4. }
  5. }
  6. class MyComponent {
  7. // specify the property on the element instance type
  8. props: {
  9. foo?: string;
  10. }
  11. }
  12. // element attributes type for 'MyComponent' is '{foo?: string}'
  13. <MyComponent foo="bar" />

The element attribute type is used to type check the attributes in the JSX.Optional and required properties are supported.

  1. declare namespace JSX {
  2. interface IntrinsicElements {
  3. foo: { requiredProp: string; optionalProp?: number }
  4. }
  5. }
  6. <foo requiredProp="bar" />; // ok
  7. <foo requiredProp="bar" optionalProp={0} />; // ok
  8. <foo />; // error, requiredProp is missing
  9. <foo requiredProp={0} />; // error, requiredProp should be a string
  10. <foo requiredProp="bar" unknownProp />; // error, unknownProp does not exist
  11. <foo requiredProp="bar" some-unknown-prop />; // ok, because 'some-unknown-prop' is not a valid identifier

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.

Additionally, the JSX.IntrinsicAttributes interface can be used to specify extra properties used by the JSX framework which are not generally used by the components’ props or arguments - for instance key in React. Specializing further, the generic JSX.IntrinsicClassAttributes<T> type may also be used to specify the same kind of extra attributes just for class components (and not Function Components). In this type, the generic parameter corresponds to the class instance type. In React, this is used to allow the ref attribute of type Ref<T>. Generally speaking, all of the properties on these interfaces should be optional, unless you intend that users of your JSX framework need to provide some attribute on every tag.

The spread operator also works:

  1. var props = { requiredProp: "bar" };
  2. <foo {...props} />; // ok
  3. var badProps = {};
  4. <foo {...badProps} />; // error

Children Type Checking

↥ back to top

In TypeScript 2.3, TS introduced type checking of children. children is a special property in an element attributes type where child JSXExpression_s are taken to be inserted into the attributes.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.

  1. declare namespace JSX {
  2. interface ElementChildrenAttribute {
  3. children: {}; // specify children name to use
  4. }
  5. }
  1. <div>
  2. <h1>Hello</h1>
  3. </div>;
  4. <div>
  5. <h1>Hello</h1>
  6. World
  7. </div>;
  8. const CustomComp = (props) => <div>{props.children}</div>
  9. <CustomComp>
  10. <div>Hello World</div>
  11. {"This is just a JS expression..." + 1000}
  12. </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.

  1. interface PropsType {
  2. children: JSX.Element
  3. name: string
  4. }
  5. class Component extends React.Component<PropsType, {}> {
  6. render() {
  7. return (
  8. <h2>
  9. {this.props.children}
  10. </h2>
  11. )
  12. }
  13. }
  14. // OK
  15. <Component name="foo">
  16. <h1>Hello World</h1>
  17. </Component>
  18. // Error: children is of type JSX.Element not array of JSX.Element
  19. <Component name="bar">
  20. <h1>Hello World</h1>
  21. <h2>Hello World</h2>
  22. </Component>
  23. // Error: children is of type JSX.Element not array of JSX.Element or string.
  24. <Component name="baz">
  25. <h1>Hello</h1>
  26. World
  27. </Component>

The JSX result type

↥ back to top

By default the result of a JSX expression is typed as any.You can customize the type by specifying the JSX.Element interface.However, it is not possible to retrieve type information about the element, attributes or children of the JSX from this interface.It is a black box.

Embedding Expressions

↥ back to top

JSX allows you to embed expressions between tags by surrounding the expressions with curly braces ({ }).

  1. var a = <div>
  2. {["foo", "bar"].map(i => <span>{i / 2}</span>)}
  3. </div>

The above code will result in an error since you cannot divide a string by a number.The output, when using the preserve option, looks like:

  1. var a = <div>
  2. {["foo", "bar"].map(function (i) { return <span>{i / 2}</span>; })}
  3. </div>

React integration

↥ back to top

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

  1. /// <reference path="react.d.ts" />
  2. interface Props {
  3. foo: string;
  4. }
  5. class MyComponent extends React.Component<Props, {}> {
  6. render() {
  7. return <span>{this.props.foo}</span>
  8. }
  9. }
  10. <MyComponent foo="bar" />; // ok
  11. <MyComponent foo={0} />; // error

Factory Functions

↥ back to top

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

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

emits as:

  1. const preact = require("preact");
  2. 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.