TypeScript
CrossLead Engineering - 1/3/17
- Syntax Differences
- Type System
- Development Workflow
Syntax Differences
function add(a, b) {
return a + b;
}
TypeScript ⊃ ES5
Syntax Differences: Iterator Symbol
const s = new Set([1,3,4,5,6]);
// when targeting es5 or less,
// doesn't work => runtime error if file is JS...
for (let el of s) {
//..
}
// does work
for (let el of Array.from(s)) {
//..
}
TypeScript ⊅ ES6
Syntax Differences: New Syntax
// enumeration object
enum STATUS {
ACTIVE,
DISABLED
}
// instance prop
class User {
constructor(public name, private id) {}
}
namespace Tyr {
export function collection() {}
}
Type System: Annotations
function add(a: number, b: number) {
return a + b;
}
Type System: Type Aliases
type Status = 'ACTIVE' | 'INACTIVE' | 'DELETED';
type List = {
element: number,
next: List | void
};
type HasA = { a: string };
type HasB = { b: Status };
type HasBoth = HasA & HasB; // { a: string, b: Status }
type A = HasA['a']; // string
function myFunction(a: number): number { //... }
type NumberToNumberFn = typeof myFunction; // (a: number) => number
Type System: Type Predicates
interface PromiseLike {
then(): number;
}
function isPromiseLike(obj: any): obj is PromiseLike {
return (
obj &&
obj.then &&
typeof obj.then === 'function'
);
}
Type System: Mapped Types
const a = {
x: 1,
y: 2,
z: 'hello'
};
const AType = typeof a;
const KeyOfA = keyof AType; // -> 'x' | 'y' | 'z';
type OptionalATypes = {
[P in KeyOfA]?: AType[P];
}
Type System: Interfaces + Generics
interface ID_able {
id: number;
}
interface ID_and_prop extends ID_able {
prop: string;
}
class Test implements ID_and_prop {}
interface Constructable<T> {
new (...args: any[]): T;
}
Type System: Generics continued
Type System: Declaration Files
// -> import gulp from 'gulp'; -> gulp: any;
declare module 'gulp';
// declare module with some type information
declare module 'jquery' {
var $: Function;
export default $;
}
// augment existing interface
declare module 'express' {
interface Request {
user: Tyr.User;
}
}
Development Workflow
- tsconfig.json
- @types
Development Workflow: Best Practices
- Interface Composition
- Type files
- Function parameters
- Use interfaces for complex, type alias for simple/primative
Resources
TypeScript
By Ben Southgate
TypeScript
- 854