11.09.2015 Views

Typescript Deep Dive by Basarat Ali Syed

Typescript Deep Dive by Basarat Ali Syed

Typescript Deep Dive by Basarat Ali Syed

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

TypeScript <strong>Deep</strong> <strong>Dive</strong><br />

JSX Support<br />

TypeScript supports JSX transpilation and code analysis. If you are unfamiliar with JSX here is an excerpt from the official<br />

website:<br />

JSX is a XML-like syntax extension to ECMAScript without any defined semantics. It's NOT intended to be<br />

implemented <strong>by</strong> engines or browsers. It's NOT a proposal to incorporate JSX into the ECMAScript spec itself. It's<br />

intended to be used <strong>by</strong> various preprocessors (transpilers) to transform these tokens into standard ECMAScript.<br />

The motivation behind JSX is to allow users to write HTML like views in JavaScript so that you can:<br />

Have the view Type Checked <strong>by</strong> the same code that is going to check your JavaScript<br />

Have the view be aware of the context it is going to operate under (i.e. strethen the controller-view connection in<br />

traditional MVC)<br />

This decreases the changes of errors and increases the maintainability of your user interfaces. The main consumer of JSX<br />

at this point is ReactJS from facebook. This is the usage of JSX that we will discuss here.<br />

Setup<br />

Use files with the extension .tsx (instead of .ts ).<br />

Use "jsx" : "react" in your tsconfig.json 's compilerOptions .<br />

Install the definitions for JSX and React into your project : ( tsd install react --save --resolve ).<br />

Import react into your .tsx files ( import * as React from "react" ).<br />

HTML Tags vs. Components<br />

React can either render HTML tags (strings) or React components (classes). The JavaScript emit for these elements is<br />

different ( React.createElement('div') vs. React.createElement(MyComponent) ). The way this is determined is <strong>by</strong> the case of<br />

the first letter. foo is treated as an HTML tag and Foo is treated as a component.<br />

Type Checking<br />

HTML Tags<br />

An HTML Tag foo is to be of the type JSX.IntrinsicElements.foo . These types are already defined for all the major tags in<br />

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:<br />

declare module JSX {<br />

interface IntrinsicElements {<br />

a: React.HTMLAttributes;<br />

abbr: React.HTMLAttributes;<br />

div: React.HTMLAttributes;<br />

span: React.HTMLAttributes;<br />

}<br />

}<br />

/// so on ...<br />

Components<br />

JSX<br />

69

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!