typescript.txt (1910B)
1 TypeScript 2 ========== 3 4 Remember, the whole point of using TypeScript is to use its typechecker to stop 5 you from doing invalid things. 6 7 TypeScript gives you error messages in your text editor, as you type. 8 9 But we should use type annotations only when necessary, and let TypeScript work 10 its inference magic for us whenever possible. 11 12 13 Avoid using any as type 14 ----------------------- 15 16 any makes your value behave like it would in regular JavaScript, and totally 17 prevents the typechecker from working its magic. When you allow any into your 18 code you're flying blind. Avoid any like fire, and use it only as a very very 19 last resort. 20 21 22 public keyword in class constructor 23 ----------------------------------- 24 25 class Person { 26 constructor(public firstname: string); 27 } 28 29 public is shorthand for this.firstName = firstName 30 31 32 Index signatures 33 ---------------- 34 35 let a: { 36 b: number; 37 c?: string; 38 [key: number]: boolean; 39 }; 40 41 The [key: T]: U syntax is called an index signature, and this is the way you 42 tell TypeScript that the given object might contain more keys. 43 44 a = { b: 1, c: "d", 10: true, 20: false }; 45 46 For this object, all keys of type T must have values of type U. 47 48 49 Type Alias 50 ---------- 51 52 Type aliases are useful for DRYing up repreated complex types. 53 54 55 Arrays 56 ------ 57 58 TypeScript supports two syntaxes for arrays: T[] and Array<T>. They are 59 indentical both in meaning and in performance. 60 61 62 JavaScript Generator 63 -------------------- 64 65 Append a * to function makes it a generator: 66 67 function* countUpTo(max) { 68 let count = 1; 69 while (count <= max) { 70 yield count; // Yield the current count 71 count++; 72 } 73 } 74 75 const counter = countUpTo(3); 76 console.log(counter.next().value); // 1 77 console.log(counter.next().value); // 2 78 console.log(counter.next().value); // 3 79 console.log(counter.next().value); // undefined