Skip to content

Instantly share code, notes, and snippets.

@anuraghazra
Created September 12, 2022 17:27
Show Gist options
  • Save anuraghazra/c39eb15398e39c151a6534da2ab6ea73 to your computer and use it in GitHub Desktop.
Save anuraghazra/c39eb15398e39c151a6534da2ab6ea73 to your computer and use it in GitHub Desktop.

Variables

const shade = 100;
type Shade = 100;

Functions

function hello(msg: string = "Anurag") {
  return `Hello ${msg}`;
}

type Hello<Msg extends string = "Anurag"> = `Hello ${Msg}`;

Arrays or Lists

const colors = ["red", "green", "blue"];
type Colors = ["red", "green", "blue"];
// or unions   "red" | "green" | "blue"

Conditionals

function isRGB(color: string) {
  return colors.includes(color) ? true : false;
}

type isRGB<Color extends string> = Color extends Colors ? true : false;

Loops or Mapped types

const shades = colors.map((color) => `${color}.${shade}`);
type Shades = { [Color in Colors]: `${Color}.${Shade}` }[Colors];

Recursion

// fillArray(10) -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
function fillArray(limit: number, value: Array<number> = []) {
  if (value.length >= limit) return value;
  return fillArray(limit, [...value, value.length]);
}

type FillArray<
  Limit extends number,
  Value extends Array<number> = []
> = Limit extends Value["length"]
  ? Value
  : FillArray<Limit, [...Value, Value["length"]]>;

type Demo = FillArray<10>;

Object.keys

const obj = {
  name: "anurag",
  age: 20,
};

const keys = Object.keys(obj); // ['name', 'age]
type Keys = keyof typeof obj; // 'name' | 'age

Property access

const name = obj["name"]; // 'anurag'
type Name = typeof obj["name"] // 'anurag'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment