Tuesday, 28 February 2023

typescript

 1. commands

  • npm install -g typescript         // install typescript
  • tsc index.ts                              // compile .ts to .js
  • tsc                                           // compile all src files in the src folder specified in tsconfig.json
  • tsc --init                                  // create tsconfig.json

2. tsconfig.json
  • 'sourcemap'       // enable debugging

3. tuple
  • a new type in typescript to store data in an unchanging array
  • can have different types of data

4. debug in intellij
  • use 'ts-node'                 // no need to explicitly compile typescript to javascript, see ref 2 app
  • compile & debug         // explicitly compile first (manual or script in package.json)
  • there's a typescript widget at the bottom of intellij, where you can compile

5. file extensions
  • .ts                   // source code
  • .d.ts                // declaration file
  • .tsx                 // contain jsx syntax
  • .jsx                 // allow html syntax within javascript code

6. type predicate
  • argumentName is Type
  • always attached to a function that takes a single argument and returns a boolean
interface Cat {
  numberOfLives: number;
}
interface Dog {
  isAGoodBoy: boolean;
}

function isCat(animal: Cat | Dog): animal is Cat {
  return typeof animal.numberOfLives === 'number';
}


7. interface
  • type alias

8. generic

function removeFirstOrder<T>(arr: Array<T>): Array<T> {
    arr.shift()
    return arr
}

removeFirstOrders([1, 2, 3, 4])
removeFirstOrders(['a', 'b', 'c', 'd'])


reference