Skip to content

Instantly share code, notes, and snippets.

@larrybahr
Created November 6, 2021 15:25
Show Gist options
  • Save larrybahr/2fc4b80027bcd50ce9d3eb18f5c12eab to your computer and use it in GitHub Desktop.
Save larrybahr/2fc4b80027bcd50ce9d3eb18f5c12eab to your computer and use it in GitHub Desktop.
TypeScript Cheet Sheet

tools

Repl https://www.typescriptlang.org/play

over view https://github.com/ruizb/glossary-typescript

Optional Chaining - foo?.bar.baz();

Guard Functions

in operator - narrow down types

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

https://www.youtube.com/watch?v=eJ6R1knfsoc&t=160s

if ('make' in car === false) {
  car.make = 'Suzuki';
}

type predicates - Custom typeof function

https://www.typescriptlang.org/docs/handbook/advanced-types.html#using-type-predicates

https://www.youtube.com/watch?v=eJ6R1knfsoc&t=237s

type Car = {
    wheels: number
};

type Boat = {
    isSaltWater: boolean
}

type Vehicle = Car | Boat;

// Type Predicate
const isCar = (v: Vehicle): v is Car => {
    return 'wheels' in v;
};

(function (a: Vehicle)
{
    if(isCar(a))
    {
        console.log(a.wheels);
    }

})({isSaltWater: true});

Assert functions - throw error if not right type

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions

https://www.youtube.com/watch?v=eJ6R1knfsoc&t=580s

/*
The first type of assertion signature models the way that Node’s assert function works. It ensures that whatever condition is being checked must be true for the remainder of the containing scope.
*/
function assert(condition: any, msg?: string): asserts condition {
  if (!condition) {
    throw new AssertionError(msg);
  }
}

// must be a string
function assertIsString(val: any): asserts val is string {
  if (typeof val !== "string") {
    throw new AssertionError("Not a string!");
  }
}

// value cannot be null or undefined 
function assertIsDefined<T>(val: T): asserts val is NonNullable<T> {
  if (val === undefined || val === null) {
    throw new AssertionError(
      `Expected 'val' to be defined, but received ${val}`
    );
  }
}

Lookup Type - access no explicit sub type Type['prop']

https://www.youtube.com/watch?v=eJ6R1knfsoc&t=753s

type Person = {
    name: string;
    address: {
        city: string;
        state: string;
        zip: number;
    }
}

type Address = Person['address'];

const a: Address = { city: '', state: '', zip: 0 };

Generics - like function params, but with Types

https://www.youtube.com/watch?v=eJ6R1knfsoc&t=845s

enum InputTypes {
    email = 'email',
    phone = 'phone'
}

type UserInput<T = InputTypes> = {
    value: string;
    type: T
}

const field1: UserInput = {
    value: '',
    type: InputTypes.email
};
field1.type = InputTypes.phone;

const field2: UserInput<InputTypes.email> = {
    value: '',
    type: InputTypes.email
};
// Error Type 'InputTypes.phone' is not assignable to type 'InputTypes.email'.
// field2.type = InputTypes.phone;

Conditional Types

https://www.youtube.com/watch?v=eJ6R1knfsoc&t=1414s

type Diesel = { type: 'petroleum' | 'bio'}
type Gasoline = { type 'hybrid' | 'conentional'}
type Bus = { engine: Diesel }
type Car = { engine: Gasoline }
type Bicycle = { power: 'limbs' }
type Engine<T> = T extends { engine: unknown } ? T['engine'] : never;

const carEngine: Engine<Car> = {
    type: 'hybrid'
}

// Engine<Bicycle> has a type of never
// Gets error 'only `never` can be assigned to `never`
const BikeEngine: Engine<Bicycle> = { power: 'limbs' };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment