JSX support

JSX is an embeddable XML-like syntax. It is meant to be transformed into valid JavaScript, but the semantics of that transformation are implementation-specific. JSX came to popularity with the React library but has since seen other applications. TypeScript 1.6 supports embedding, type checking, and optionally compiling JSX directly into JavaScript.

New .tsx file extension and as operator

TypeScript 1.6 introduces a new .tsx file extension. This extension does two things: it enables JSX inside of TypeScript files, and it makes the new as operator the default way to cast (removing any ambiguity between JSX expressions and the TypeScript prefix cast operator). For example:

  1. var x = <any> foo;
  2. // is equivalent to:
  3. var x = foo as any;

Using React

To use JSX-support with React you should use the React typings. These typings define the JSX namespace so that TypeScript can correctly check JSX expressions for React. For example:

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

Using other JSX frameworks

JSX element names and properties are validated against the JSX namespace. Please see the [[JSX]] wiki page for defining the JSX namespace for your framework.

Output generation

TypeScript ships with two JSX modes: preserve and react.

  • The preserve mode will keep JSX expressions as part of the output to be further consumed by another transform step. 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.See the [[JSX]] wiki page for more information on using JSX in TypeScript.