Skip to content

Instantly share code, notes, and snippets.

@npodonnell
Last active April 17, 2021 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save npodonnell/9ca429eaabccbd99f17de2c00b78fd9b to your computer and use it in GitHub Desktop.
Save npodonnell/9ca429eaabccbd99f17de2c00b78fd9b to your computer and use it in GitHub Desktop.
TypeScript Cheatsheet

TypeScript Cheatsheet

N. P. O'Donnell, 2020

Facts about TypeScript

  • Files end in .ts.
  • TypeScript is a superset of JavaScript, similar to how C++ is a superset of C. All JavaScript is valid TypeScript.
  • Compiles down to JavaScript.

Installing

Run with sudo:

npm install -g typescript

Check version of tsc:

tsc -v

Compiling TypeScript

To compile main.ts:

tsc main.ts

-or-

tsc main

To continually compile main.ts:

tsc main.ts --watch

tsconfig.json File

To create a tsconfig.json file:

tsc --init

Language

Types :)

TypeScript has 3 primitive types: boolean, number and string. These are the same as in JS, but in TS the type can be enforced. The following lines are both valid TS:

let x1 = true;             // x1 is now a boolean and can not be set to anything else other than false
let x2: boolean = true;    // x2 is now a boolean and can not be set to anything else other than false

The following won't compile though:

let x3: boolean = "lol"; // Makes no sense right?

JavaScript's null and undefined are kinda weird beause they are values (as in JS) but they are also TypeScript types:

let n: null = null;
let u: undefined = undefined;

As in JS, other type variables may also be set to null or undefined.

Arrays

To define an array of things of a particular type there are 2 choices of syntax, which are semantically the same:

let list1: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3];

Tuples

A tuple is free-form structure which amounts to an array containing different types:

let person1: [string, number] = ["Chris", 22];

Enums

Enums are similar to Java/C++ enums:

enum Color {Red, Green, Blue};
let c:Color = Color.Green;

On transpilation, enums are converted to zero-indexed integer numbers:

> console.log(c);
1

Arbitrary numbers can also be used:

enum Color {Red = 5, Green, Blue};

This makes Green 6 and Blue 7.

Any

any is a special type which allows a variable to be set to any type:

let randomValue: any = 10;
randomValue = true;           // This is cool
randomValue = "Vishwas";      // This is cool too

Type Union

Type union allows a variable to take on a finite number of types:

let multiType: number | boolean;
multiType = 20;    // Cool
multiType = true;  // Cool too
multiType = "yay"; // Not cool

Interfaces

Interfaces are a way of defining structured objects, similar to C structs:

interface Person {
  firstName: string;
  lastName: string;
}

An interface can be given an optional property by appending a ? to the property name:

interface Person {
  firstName: string;
  middleName?: string;
  lastName: string;
};

To instantiate an instance of Person:

const jay: Person = {
  firstName: "Jay";
  lastName: "Leno";
};

Big Integers

Big Integers have the type name bigint. They can also be constructed from strings or nubmers with BigInt(...) or specified as literals by appending a n:

const x:bigint = BigInt("1244562334534243634346534536");
const y:bigint = 2543654677752342323675676n;
const z = x * y;
console.log(z.toString()); // 3165736803992404355885757290099418853694696197146336

Examples

Promises

Promise's in TypeScript are typically Promise<T>'s:

function retProm(): Promise<string> {
    return new Promise<string>((resolve, reject) => {
        setTimeout(() => {
            if (Math.random() < 0.5) {
                resolve("Good!");
            } else {
                reject("Bad!");
            }
        }, 1000)
    })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment