Page History

ts_cheat_sheet

dmsc edited this page on 30 Nov

Clone this wiki locally

My TypeScript Cheat Sheet

Adding TypeScript to a project

  • add TypeScript compiler to package.json
    npm install -D typescript --save
    or
    "devDependencies": {
      "typescript": "<version>"
    }
  • The available versions can be found on npm.
  • in the scripts section add
    "scripts": {
      "compile": "tsc",
      "watch": "tsc --watch"
    }
  • then install dependencies using npm install
  • create the tsconfig.json file using npm run compile -- --init
  • run npm run compile or npm run watch

Debugging in VS code with nodejs

...

Debugging in VS Code with Chromium

Enable source maps in tsconfig.json

"sourceMap": true

Attach to Chromium using remote debugging port

chromium --remote-debugging-port=9222 --disable-web-security --user-data-dir=remote-debug-profile > /dev/null &

Contents of launch.json

{
    //chromium --remote-debugging-port=9222 --user-data-dir=remote-debug-profile > /dev/null &
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "attach",
            "name": "attach to browser",
            "port": 9222,
            "url":"http://localhost:3000",
            "webRoot": "${workspaceFolder}/example_folder"
        }
    ]
}

Syntax

var

  • Variable declaration without block scope (block meaning function, if-else block or for-loop)
  • Variables declared that way in a block are 'hoisted' to the surrounding function.
  • If used in a function variables are function-scoped.
  • Variables can be read or written before they are declared.

let

Does support block scope.

  • block-scoped variables cannot be read or written before they are declared
  • let-variables cannot be re-declared

const

Declaration of 'constants'.

  • Same scoping rules as let variables
  • The variable value can't be changed once declared.
  • The variable can't be reassigned.
  • Objects declared that way are not immutable. Instance properties can be changed but not the object structure.
  • Does support block scope.

function

function myExampleFunction(param1: typeX,..., paramN: typeY): returnTypeZ { function body }

Lamba function / Fat arrow notation

  • Used for anonymous functions
  • function keyword is dropped
    (param1, param2, ..., paramN) => { function body }
    Example:
    exampleList.forEach(item => {
      console.log('blah');
    })
    Example 2 (without parameters):
  • if the functions body consists of only one statement curly brackets are not needed
    let hello = () => console.log('Hello World!');

for

const numbers = [1, 2, 3]
for (let i = 0, i < numbers.length, i++) {
    const number = numbers[i]
    console.log(number);
}

for .. of

Loops over the values/members of an iterable object (using Symbol.iterator -> works only with iterables)

const myList: string[] = ["A", "B", "C"];
for (let item of myList) {
    console.log(item);  //"A", "B", "C" // values
}

for .. in

Loops over a list of keys on the object. The assigned variable ("index" in this case) holds only the members index.

const myList: string[] = ["A", "B", "C"];
for (let item in myList){
    console.log(item); //0, 1, 2 // keys
}

Enums

//Numeric Enum (default initialization - no numeric values set)
enum Trees {
    Birch,
    Redwood,
    Pine
}

let currentTree = Trees.Pine;
console.log(currentTree);

// String Enum
enum StringEnum {
    Hi = "HI",
    Bye = "BYE"
}

let currentString = StringEnum.Hi;
console.log(currentString);

Promises

let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)

  myResolve(); // when successful
  myReject();  // when error
});

// "Consuming Code" (Must wait for a fulfilled Promise)
myPromise.then(
  function(value) { /* code if successful */ },
  function(error) { /* code if some error */ }
);

(from w3schools)

async & await

  • simplify writing promises
  • async makes a function return a Promise
  • await makes a function wait for a promise

Basic types

  • boolean: true or false
  • number: floating point number
  • string

    Template strings

    Example: let cool: string = `${hello} ${world}`

OOP

  • Typescript does not support multiple inheritance
  • inheritance defines a is_a relationship
  • an interface defines a has_a relationship
    • interfaces only contain public method signatures (method names, inputs and outputs) and public constants
    • implementing an interface means implementing each and every method of the interface
    • typescript interfaces can't be transpiled to JavaScript (their code just does not show up in tsc output)

Abstract Classes

  • can't be instantiated but can be inherited from (using extends)
  • can have abstract methods
  • descendants must implement abstract methods to make them concrete
  • have a constructor that descendants which have a constructor themselves must call first using the super keyword

Modules

  • By default TS code is in the global scope.
  • Files containing a top-level export or import statement are considered modules
  • Modules are executed in their own scope not in the global scope -> classes, functions, variables cannot be accessed or altered (in the case of variable-values) without prior import

exampleFile1.ts

export let exampleVar: number = 20;
export class ExampleClass {
    blah: number;
    constructor(blah: number) {
        this.blah = blah;
    }
}

exampleFile2.ts

Import { ExampleClass } from exampleFile1  // no file extension

Member visibility

  • public: A public member can be accessed anywhere
  • protected: Members are only visible to subclasses of the class they're declared in
  • private: Like protected but members cannot be accessed from subclasses. Member properties can only be accessed within their class.

Constructor

export class ClassExample {
    constructor(
        public firstEx: string,
        public secondEx: number,
        public thirdEx?:string 
    )
}
  • ? in thirdEx specifies that it's an optional field

Tools

npm

  • npm init: creates a new package defined by a package.json file.
  • npm install: install dependencies listed in package.json.
  • npm update: install available updates to dependency packages.
  • npm outdated: get a list of packages that need to be updated.

Gotchas >>

Links