The document introduces TypeScript, describing it as a superset of JavaScript that adds optional static types and transpiles some ECMAScript 2015+ features. It discusses TypeScript's structural type system and type inference, provides examples of structural typing and generics, and describes how to define types for external libraries, write tests, and build a TypeScript project.
2. What is TypeScript
• typescriptlang.org
• Superset of JavaScript
• Optional static types
• Transpiles some js.next() features
• Targets ES3, ES5, and ES6 (new in TypeScript 1.4)
4. Structural Types
interface Named {
name: string;
}
class Person {
name: string;
}
var p: Named;
// OK, because of structural typing
p = new Person();
5. Structural Types
interface Named {
name: string;
}
var x: Named;
// y's inferred type is { name: string; location: string; }
var y = { name: 'Alice', location: 'Seattle' };
x = y;
6. Structural Types
var x = (a: number) => 0;
var y = (b: number, s: string) => 0;
y = x; // OK
x = y; // Error
7. Type Inference
var x = 3;
// x: number
// Window.onmousedown: (ev: MouseEvent) => any
window.onmousedown = function(mouseEvent) {
console.log(mouseEvent.buton); //<- Error
};
8. Generics
interface Monoid<T> {
zero: T;
add: (x: T, y: T) => T;
}
var sum: Monoid<number> = {
zero: 0,
add: (x, y) => x + y
}
var product: Monoid<number> = {
zero: 1,
add: (x, y) => x * y
}
function reduce<T>(list: T[], monoid: Monoid<T>): T {
return list.reduce((acc, x) => monoid.add(acc, x), monoid.zero);
}
console.log(reduce([2, 4, 6], sum)); // 12
console.log(reduce([2, 4, 6], product)); // 48
10. Definition Files
• Annotate non-TypeScript libraries with types
• Definitions are trusted, not checked
• Write your own or download someone else’s
11. Using Definition Files
• Cool kids provide .d.ts
github.com/Reactive-Extensions/RxJS/tree/master/ts
github.com/facebook/immutable-js/tree/master/type-definitions
• DefinitelyTyped
github.com/borisyankov/DefinitelyTyped
unofficial, uneven, but good for popular libraries
• TSD: TypeScript Definition Manager
definitelytyped.org/tsd
bundler/npm/bower for .d.ts files
12. Working with vim
• typescript-vim
https://github.com/leafgarland/typescript-vim
syntax highlighting, no indentation
• vim-js-indent
https://github.com/jason0x43/vim-js-indent
• typescript-tools
https://github.com/clausreinke/typescript-tools
code completion, type interrogation, quickfix
not yet compatible with 1.4 (issue #39)
16. Beware any
var square = (n: number): number => n * n;
var json: string = '"not a number"';
var edge: number = JSON.parse(json);
var area: number = square(edge.width);
console.log("The area of the square is", area)
// The area of the square is NaN