TypeScript Cheat Sheet

Not everything from Microsoft has to be bad.

(But to be fair, it is not hard to improve JS either.)

#Non-JS Features

Introduction

TypeScript is an extension of the JavaScript language. Under the hood, everything is transformed into JavaScript, yet TypeScript offers not only types, but also completely new things.

Unions

let someVariable:string|number 

someVariable = "Some text" 
typeof(someVariable) // string

someVariable = 420
typeof(someVariable) // number
With a union you can define several possible data types for a variable. The type is then decided depending on what is stored.

Enums - constant

enum Directions {
    North,
    South,
    West,
    East
} 
Directions.North // 0
Directions.West // 2
Enum stands for enumeration.
Starting at 0, counting is done from top to bottom and a number is assigned to each element. 0, 1, 2, etc.

Enums - not constant

enum Directions {
    North=1,
    South,
    West=10,
    East
}
Directions.South // 2
Directions.East // 11
You can assign a value on your own. Underneath it is simply increased by 1. This is not called a constant enum, because there is no constant / linear increase gsdfgdgfdsfgsdgdfgdsfsfsdfsfd

#Functions

Functions without types

function printUsername(username) {
    console.log(username)
}

printUsername("Max") // "Max"
TypeScript offers static types. But they do not need to be used in functions. Since we do not specifiy what should be passed into the function, we can pass anything with an error.

Functions using types

function printUsername(username: string):void {
    console.log(username)
}

printUsername("Max") // "Max"
In the prevoius example, we did not use types. But it makes sense, since a username only can be a string. Also, our function will never return anything, so we can use :void to.

Arrow Functions

const printUsername = (username) => {
    console.log(username)
}

printUsername("Max")
const printUsername = (username: string): void => {
    console.log(username)
}

printUsername("Max")
Also in TypeScript there are Arrow Function. They work the same as in JS. Types are optional too here.