An introduction to the first JavaScript compiler-thingy you should consider caring about.
Frontend Awesome!!
April 16, 2015
Web Developer
Geek
Dad
Javascript Fanatic
Amateur Professional Eater
eran.sh @EranSchoellhorn
TypeScript
Javascript
(Just as SASS is to CSS)
var items = getItems();
var goSportsTeam = true;
var dragonball = 'z';
some-javascript.js
some-typescript.ts
> 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
> Open Source! github.com/Microsoft/TypeScript
> JavaScript for Grown-ups ;)
What does it give us?
JavaScript, Python,
Ruby, PHP
C, C++, C#, JADE, Java, Fortran, Haskell
var number = 5;
number = "Hello!";
//👍np, bro!
int a = 10;
a = "Hello!";
//🔥Compiler Error
function numberCruncher (numA, numB){
return numA + numB;
}
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
}
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
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
var foo : any;
declare var jQuery : any;
jQuery.get('/awesome.html');
foo = 'Hello!';
foo = true;
foo = 42;
Restores basic JavaScript dynamic typing behavior
function initSomething() : void {
doSomeStuff();
}
var pointless = initSomething(); // 🍋Compiler Error
A function that returns nothing
Basically ES6 import module syntax. Compiles into AMD, CommonJS, or vanilla ES6 JS.
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!
1.4 is stable now. 1.5 has more ES6 features, still in alpha.