Typescript
TypeScript is a strongly typed programming language which builds on JavaScript giving you better tooling at any scale.

Table of Contents

Static attributes and methods

Static methods can be called on the class directly:

class Pony {
  static defaultSpeed() {
    return 10;
  }
}

const speed = Pony.defaultSpeed();

Promises

const getUser = (login) => {
  return new Promise((resolve, reject) => {
    if (response.status === 200)
      resolve(response.data);
    else
      reject('No user');
  });
};

getUser(login)
  .then(user => console.log(user));

Union

If a variable is require to have multiple types exclusively.

let changing: number | boolean = 2;
changing = true;

Enums

By default enum starts with 0.

enum Status { Ready, Started, Done }
const progress = Status.Started;

But custom values can also be set.

enum Medal { Gold = 1, Silver, Bronze }

Generics

To define generic types in javascript we can:

// A generic class
class Queue<T> {
    private list: T[] = [];

    push(item: T): void { this.list.push(item); }
    pop(): T | undefined { return this.list.shift() }
}

let queue = new Queue<number>();

queue.push(3);
queue.push('4'); // error!

Currying

In functional programming we often want to apply a function partially, we can achieve that feat by chaining together multiple fat arrow functions:

// A curried function
const add = (x: number) => (y: number) => x + y;

// Usage
add(123)(456);

// Partially applied
let add123 = add(123);

// fully apply the function
add123(456);

Return type

We can set the return type of a function like so:

function startRace(race: Race): Race {
  race.status = Status.Started;
  return race;
}

If the function returns nothing, return void.

Interfaces

When a function has an arguments that require a specific property, we can use interfaces to define the "shape" of that object.

function addPointsToScore(player: { score: number; }, points: number): void {
  player.score += points;
}

It means that the parameter must have a propert called score of the type number. We can name these interfaces like so:

interface HasScore {
  score: number;
}

function addPointsToScore(player: HasScore, points: number): void {
  player.score += points;
}

Optional Arguments

JS arguments are optional, but in TypeScript the compiler will complain if parameters with types are forgotten.

We can add a ? after the parameter to make it optional.

function addPointsToScore(player: HasScore, points?: number): void {
  points = points || 0;
  player.score += points;
}

Assert functions

type Email: string;

const assertValidEmail = (email: string): asserts email is Email {
    if (!email.includes('@'))
        throw new Error('Not a valid email.');
}

Utility types

Utility types are useful generic constructs to perform type transformations, more specifically, on an object. Most used utility types are:

  • Partial<T> which transforms all members of T into optional
  • Readonly<T> which, well… makes all fields read-only

    …and many more such as Record<K,T>, Pick<T,K>, Omit<T,K> etc. which I already know the behaviour of.

Brand types

type Brand<K, T> = K & { __brand: T };

Declaration files

Afaik, declaration files are used to define what the types of a javascript file are. This is useful for prividing intelisense in your text editor.

Date: 2021-09-11 sáb 00:00

Author: Bruno Coimbra (b-coimbra)

Created: 2021-10-13 qua 13:37

Validate