JSX & TypeScript – Figuring out how to use them together – Working through errors



JSX & TypeScript – Figuring out how to use them together – Working through errors

0 0


Using-Typescript-with-JSX

Presentation on using Typescript with React

On Github thewazir / Using-Typescript-with-JSX

JSX & TypeScript

How to use them together

Omer Wazir / @thewazir

Disclaimer

JSX support in TypeScript was announced Sept 2nd 2015. Almost every article on this topic rips from the JSX page on the TypeScript wiki because there’s very little officially said on the topic. This presentation is based off the same wiki post.

What & Why

  • Reliabily building large JS apps is hard
  • TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.
  • Static Types lead to better Tooling
  • Future features available today (transpiling)
  • Open Source

Some features of TypeScript

String · Number · Boolean · Enum · Any · Void · Symbols · let & const · ES7 Decorators proposal · Decorator type metadata · Interfaces · Classes · Public, private, and protected modifiers · Namespaces & Modules · Generics · Optional and Default Parameters · Rest Parameters · Function Overloading · Mixins · Declaration Merging · Structural Subtyping · Definition Files · ...and in release 1.6: JSX! · Intersection types · Local type declarations · Class expressions · Extending expressions · Abstract classes

TypeScript has MANY other features besides what you see here

Installing TypeScript

JSX support is coming in TypeScript 1.6 which is in a beta state. For now you can install these two ways

/*
* Install globally or locally - your choice
*/

//1.6.0-beta with JSX support
npm install typescript@1.6.0-beta

//Nightly build with JSX support
npm install typescript@next
							
						

Works wherever npm works

Running TypeScript

  • You can call tsc in the command line if TypeScript is installed globally.
  • Run TypeScript in a gulp task using gulp-typescript to help you.
  • Use ts-loader for WebPack
  • IDE/Editor can run TypeScript to check your code

Editor Support

Visual Studio includes TypeScript in the box, starting with Visual Studio 2013 Update 2. You can also find TypeScript support in:

  • Visual Studio Code
  • WebStorm
  • Atom
  • Sublime Text
  • and Eclipse for you crazy people

Basic usage

In order to use JSX you must do two things. and be using TypeScript 1.6 beta or nightly

Name your files with the .tsx extension Enable the jsx option in the command line or a ts.config file

React integration

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

There is TypeScript Definition manager on npm to help manage with definition files

Working through errors

Default props must be static

		
	class App extends React.Component {
	  constructor(props){
	    super(props)
	    this.state = {count: 0}
	    this.increment = this.increment.bind(this);
	  }
	  static defaultProps = {
	    txt: 'default props txt'
	  }
	...
		
	

Create Props and State interfaces

			
	import * as React from 'react';

	interface Props {
	  txt: string;
	}

	interface State{
	  count: number;
	}


	// Render a simple React component into the body.
	class App extends React.Component<Props, State> {...}
		
		

Type Variablesthis is why JSX never worked in TypeScript

Since TypeScript uses angle brackets for type casting, there was a conflict when parsing between type casting and JSX

//casting syntax
//<Type> variable

//setting span to be of a HTMLSpanElement type
let span: HTMLSpanElement;

//fails because document.createElement returns a type of HTMLElement
this.span = document.createElement('span');

//so you need to cast
this.span = <HTMLSpanElement> document.createElement('span');

Using the as operator

Angle bracket type assertions are not available in .tsx files

		
//new casting syntax
//variable as Type

//setting span to be of a HTMLSpanElement type
let span: HTMLSpanElement;

//fails becaue document.createElement returns a type of HTMLElement
this.span = document.createElement('span');

//so you can cast this way I think...
this.span = document.createElement('span') as HTMLSpanElement;

	

The as operator is available in both .ts and .tsx files.

See TypeScript issue #296 for the as operator discussion

Escaping to TypeScript

JSX in JavaScript allows you to escape to JavaScript by using curly braces { }. JSX in TypeScript allows you to do the same thing, but you escape to TypeScript. That means transpilation features and type checking still work when embedded within JSX.

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

The above code will result in an error since you cannot divide a string by a number.

Type Checking JSXIntrinsic elements vs Value-based elements

This will probably make more sense in practice than in reading the documentation

Should I use TypeScript now

  • Do you want to write ES6?
    • ES6 support up to 56% of features
  • Do you use WebStorm, Atom, or some other editor?
    • Many popular editors have packages for TypeScript
  • Do you develop on Windows?
    • One package installed via npm
    • It's a Microsoft project and C# designer Anders Hejlsberg is heavily involved
  • JSX support is in beta
  • Documentation of features could be better
JSX & TypeScript How to use them together Omer Wazir / @thewazir