⭐️ Cheat sheet

💾 TS Cheat sheet

/* ------- ⭐️ type alias -------- */
type Point = { x: number, y: number };


/* ------- ⭐️ union type -------- */

//        ╭─── union ───╮
type ID = number | string;


/* ------- ⭐️ interface -------- */
// (similar to Protocol in Swift)
interface Point2D {
  x: number;
  y: number;
}


/* ------- ⭐️ type annotation -------- */

//        ╭──────╮
let myName: string = "Alice";                   // on variable
function greet(name: string) { log(name) }      // on parameter
function twentySix(): number { return 26; }     // on return type


/* ------- ⭐️ extending types -------- */

interface Colorful { color : string; }
interface Circle   { radius: number; }
 
interface ColorfulCircle extends Colorful, Circle {}
 
const cc: ColorfulCircle = {
  color: "red",
  radius: 42,
};


/* ------- ⭐️ Intersection Types -------- */

//                   ╭─ intersection ──╮
type ColorfulCircle = Colorful & Circle ;
// produce new type that has all members of Colorful & Circle


/* ------- ⭐️ Generic type alias -------- */

// ⭐️ generic types
type Optional<T> = T | null;
type OneOrMany<T> = T | T[];
type OptioanlOneOrMany<T> = Optional<OneOrMany<T>>;  // T | T[] | null

// ⭐️ concrete type
type OptionalOneOrManyStrings = OptioanlOneOrMany<string>;
// string | string[] | null

type Box<T> = { contents: T; };

/* ------- ⭐️ Generic interface -------- */

interface Box<T> {        // `T`: type parameter
  contents: T;
}

let box: Box<string>;     // `string`: type argument


/* ------- ⭐️ Generic functions -------- */

function setContents<T>(box: Box<T>, contents: T) {
  box.contents = contents;
}

The principle difference between interface and intersection is how conflicts are handled. 📘 TypeScript ⟩ Intersection Types

Last updated