notes

Log | Files | Refs | README

typescript.md (1346B)


      1 # TypeScript
      2 
      3 Remember, the whole point of using TypeScript is to use its typechecker to stop
      4 you from doing invalid things.
      5 
      6 TypeScript gives you error messages in your text editor, as you type.
      7 
      8 But we should use type annotations only when necessary, and let TypeScript work
      9 its inference magic for us whenever possible.
     10 
     11 ## Avoid using `any` as type
     12 
     13 `any` makes your value behave like it would in regular JavaScript, and totally
     14 prevents the typechecker from working its magic. When you allow `any` into your
     15 code you're flying blind. Avoid `any` like fire, and use it only as a very very
     16 last resort.
     17 
     18 ## `public` keyword in class constructor
     19 
     20 ```ts
     21 class Person {
     22   constructor(public firstname: string);
     23 }
     24 ```
     25 
     26 `public` is shorthand for `this.firstName = firstName`
     27 
     28 ## Index signatures
     29 
     30 ```ts
     31 let a: {
     32   b: number;
     33   c?: string;
     34   [key: number]: boolean;
     35 };
     36 ```
     37 
     38 The `[key: T]: U` syntax is called an index signature, and this is the way you
     39 tell TypeScript that the given object might contain more keys.
     40 
     41 ```ts
     42 a = { b: 1, c: "d", 10: true, 20: false };
     43 ```
     44 
     45 For this object, all keys of type T must have values of type U.
     46 
     47 ## Type Alias
     48 
     49 Type aliases are useful for DRYing up repreated complex types.
     50 
     51 ## Arrays
     52 
     53 TypeScript supports two syntaxes for arrays: `T[]` and `Array<T>`. They are
     54 indentical both in meaning and in performance.