CrossLead Engineering - 1/3/17
function add(a, b) {
return a + b;
}
TypeScript ⊃ ES5
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
// enumeration object
enum STATUS {
ACTIVE,
DISABLED
}
// instance prop
class User {
constructor(public name, private id) {}
}
namespace Tyr {
export function collection() {}
}
function add(a: number, b: number) {
return a + b;
}
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
interface PromiseLike {
then(): number;
}
function isPromiseLike(obj: any): obj is PromiseLike {
return (
obj &&
obj.then &&
typeof obj.then === 'function'
);
}
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];
}
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;
}
// -> 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;
}
}