TypeScript!

An introduction to the first JavaScript compiler-thingy you should consider caring about.

Frontend Awesome!!

April 16, 2015

Eran

Web Developer

Schoellhorn

Geek

Dad

Javascript Fanatic

Amateur Professional Eater

eran.sh          @EranSchoellhorn

The skinny:

  • What is it?
  • Where did it come from?
  • What are its goals?
  • How can I use it?
  • What happens in the future?

TypeScript
!==
CoffeeScript

TypeScript is a superset of JavaScript

TypeScript

Javascript

(Just as SASS is to CSS)

  var items = getItems();
  var goSportsTeam = true;
  var dragonball = 'z';

some-javascript.js

some-typescript.ts

Most pre-existing JavaScript

is already valid TypeScript

Backstory

> Developed by Microsoft (I know, I know..)

> First public appearance: October 1, 2012

> Stable release: 1.4 released January 16, 2015

> Conforms to ECMA standards & proposals

> JavaScript for Grown-ups ;)

Static Types

ECMAScript 6

What does it give us?

...and more!

Dynamic

JavaScript, Python,
Ruby, PHP

Static

C, C++, C#, JADE, Java, Fortran, Haskell 

Typing....

  var number = 5;
  number = "Hello!";
  //👍np, bro!
  int a = 10;
  a = "Hello!"; 
  //🔥Compiler Error 

  function numberCruncher (numA, numB){
    return numA + numB;
  }

JavaScript

var result = numberCruncher(5, 5);
console.log(result); 
>> 10
result = numberCruncher(5, true);
console.log(result); 
>> 6 😒
result = numberCruncher(5, 'js4lyfe');
console.log(result); 
>> "5js4lyfe" 😁
result = numberCruncher(5, {param: true});
console.log(result); 
>> "5[object Object]" 👀🔫
  function myTypedFunction(paramName : dataType) : returnType {
    // Regular junk here
  }

Typing with TypeScript

  var varName : string = 'Yeah baby!';

Type a variable:

Type a function:

  function trimLength(inputVal : string) : number {
    return inputVal.trim().length;
  }

Available Types:

Standard JS Types: Boolean, Number, String, Array

Also includes Enum, Any, Void

Arrays


  var myNumbers : number[] = [170, 2.6, 2245, 3032, 400];

  // Or...

  var myNumbers : Array<number> = [170, 2.6, 2245, 3032, 400];

Enforce types for array content

Any


  var foo : any;

  declare var jQuery : any;

  jQuery.get('/awesome.html');
foo = 'Hello!';
foo = true;
foo = 42;

Restores basic JavaScript dynamic typing behavior

Void


  function initSomething() : void {
    doSomeStuff();
  }
var pointless = initSomething(); // 🍋Compiler Error

A function that returns nothing

Modules

Basically ES6 import module syntax. Compiles into AMD, CommonJS, or vanilla ES6 JS.

Definitions

External files which define types for libraries that aren't necessarily written in TS. 


  // Original TS sytax
  import Something = require('something');

  // ES6
  import {Something} from './something';

  // Example time!

TypeScript!

1.4 is stable now. 1.5 has more ES6 features, still in alpha.

Made with Slides.com