Skip to content

Instantly share code, notes, and snippets.

@nickscript0
Last active April 29, 2018 03:58
Show Gist options
  • Save nickscript0/3fcf33e14912672ee2e7f438c742e18f to your computer and use it in GitHub Desktop.
Save nickscript0/3fcf33e14912672ee2e7f438c742e18f to your computer and use it in GitHub Desktop.
Typescript Cheatsheet

Basic Types

All Basic Type keywords

From https://www.typescriptlang.org/docs/handbook/basic-types.html

const bool: boolean = true;
const num: number = 5;
const str: string = 'apple';
const numArr: number[] = [1, 2, 3];
const f: Function = () => 1;

// Tuple
let aTuple: [string, number];
aTuple = ["hello", 10];

// Enum
enum Color {Red, Green, Blue}
enum Color2 {Red = 'red', Green = 'green', Blue = 3}
let c: Color = Color.Green;
let c2: Color2 = Color2.Green;

// Any
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

// Void
function warnUser(): void {
    alert("This is my warning message");
}

// Null and Undefined
let u: undefined = undefined;
let n: null = null;

// Never
// Function returning never must have unreachable end point
function error(message: string): never {
    throw new Error(message);
}

// Type assertions or Typecasting
let someValue: any = "this is a string";

let strLength: number = (<string>someValue).length;
// Equivalent to the previous line with 'as' syntax
let strLength: number = (someValue as string).length;

Interfaces

Defines an object or class structure

interface Timing {
    name: string;
    value: number;
    func: (a: number) => string;
}

const t: Timing = {
    name: 'load',
    value: 5,
    func: (a: number) => 'apple' // function type definition
};

class A implements Timing {
    name: string;
    value: number;

    constructor() {
        this.name = 'name';
        this.value = 5;
    }

    func(a: number) {
        return 'apple';
    }
}

Type Aliases

type StringOrNumber = string | number;

Advanced Types

https://www.typescriptlang.org/docs/handbook/advanced-types.html

Index Types

function pluck<T, K extends keyof T>(o: T, names: K[]): T[K][] {
  return names.map(n => o[n]);
}
let person: Person = {
    name: 'Jarid',
    age: 35
};
let strings: string[] = pluck(person, ['name']); // ok, string[]

Index Signatures

Constrain all the keys/values of an object to a certain type.

interface Map<T> {
    [key: string]: T;
}
let keys: keyof Map<number>; // string
let value: Map<number>['foo']; // number

Mapped Types

Go even further than index signatures and use rules that apply to a subset of a types properties. See the advanced types handbook for more info.

Type Guards

Used for narrowing union types.

typeof Type Guards

Can only be used for official types: These typeof type guards are recognized in two different forms: typeof v === "typename" and typeof v !== "typename", where "typename" must be "number", "string", "boolean", or "symbol". While TypeScript won’t stop you from comparing to other strings, the language won’t recognize those expressions as type guards.

function padLeft(value: string, padding: string | number) {
    if (typeof padding === "number") {
        return Array(padding + 1).join(" ") + value;
    }
    if (typeof padding === "string") {
        return padding + value;
    }
    throw new Error(`Expected string or number, got '${padding}'.`);
}

instanceof

Use these for comparing Object types

if (myInstance instanceof MyClass) {
    // type narrowed to 'MyClass'
}

User-defined

Use these when comparing user defined interfaces

function isFish(pet: Fish | Bird): pet is Fish {
    return (<Fish>pet).swim !== undefined;
}

// Both calls to 'swim' and 'fly' are now okay.

if (isFish(pet)) {
    pet.swim();
}
else {
    pet.fly();
}

String Literal Types

Specify the exact value a string must have.

type Easing = "ease-in" | "ease-out" | "ease-in-out";
class UIElement {
    animate(dx: number, dy: number, easing: Easing) {
        if (easing === "ease-in") {
            // ...
        }
        else if (easing === "ease-out") {
        }
        else if (easing === "ease-in-out") {
        }
        else {
            // error! should not pass null or undefined.
        }
    }
}

Discriminated Unions

TODO

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment