All Projects → lahin31 → typescript-cheatsheet

lahin31 / typescript-cheatsheet

Licence: other
Cheatsheet for TypeScript.

Projects that are alternatives of or similar to typescript-cheatsheet

learning-topology-synthetic-data
Tensorflow implementation of Learning Topology from Synthetic Data for Unsupervised Depth Completion (RAL 2021 & ICRA 2021)
Stars: ✭ 22 (-21.43%)
Mutual labels:  void
FSharpCheatSheet
Reference sheet of the basics of F# ^_^
Stars: ✭ 20 (-28.57%)
Mutual labels:  cheatsheet
tidal-cheat-sheet
A cheat sheet for Tidal, a language for live coding patterns
Stars: ✭ 38 (+35.71%)
Mutual labels:  cheatsheet
8086-cheatsheet
8086 Microprocessor Cheat sheet with Programs
Stars: ✭ 81 (+189.29%)
Mutual labels:  cheatsheet
hackthebox
Notes Taken for HTB Machines & InfoSec Community.
Stars: ✭ 286 (+921.43%)
Mutual labels:  cheatsheet
Nextflow cheatsheet
Tips for Nextflow and cheatsheet for channel operation
Stars: ✭ 38 (+35.71%)
Mutual labels:  cheatsheet
linux-installer
Universal GNU+Linux installer script
Stars: ✭ 16 (-42.86%)
Mutual labels:  void
cheatsheet-generator
Generates cheatsheets for your (favourite) apps
Stars: ✭ 49 (+75%)
Mutual labels:  cheatsheet
ffmpeg-cheatsheet
📼 A cheatsheet for common video processing operations in FFmpeg
Stars: ✭ 153 (+446.43%)
Mutual labels:  cheatsheet
android-convention-cheatsheet
Android Naming Convention Cheat Sheet
Stars: ✭ 52 (+85.71%)
Mutual labels:  cheatsheet
docker-cheat-sheet
Important Docker Commands Ordered by Compute (Services), Network, Storage then by Docker CLI, Dockerfile, Compose, and Swarm
Stars: ✭ 21 (-25%)
Mutual labels:  cheatsheet
vue-unit-testing-cheat-sheet
🔬 My cheat sheet for testing vue components with jest and vue-test-utils
Stars: ✭ 101 (+260.71%)
Mutual labels:  cheatsheet
CoqCheatSheet
Reference sheet for the Coq language.
Stars: ✭ 15 (-46.43%)
Mutual labels:  cheatsheet
ruuand.github.io
Wiki for stuff
Stars: ✭ 30 (+7.14%)
Mutual labels:  cheatsheet
function-composition-cheatsheet
Composition of Functions
Stars: ✭ 24 (-14.29%)
Mutual labels:  cheatsheet
voidnsrun
Run glibc binaries in musl libc Void Linux environment
Stars: ✭ 31 (+10.71%)
Mutual labels:  void
fe-store-house
The front-end resource that gathered in my working days.
Stars: ✭ 95 (+239.29%)
Mutual labels:  cheatsheet
Arduino-Cheat-Sheet
A cheat sheet for Arduino programming.
Stars: ✭ 120 (+328.57%)
Mutual labels:  cheatsheet
tldr
Simplified and community-driven man pages (tldr-pages) in a single binary.
Stars: ✭ 33 (+17.86%)
Mutual labels:  cheatsheet
gdb-cheatsheet
GDB cheatsheet for reversing binaries
Stars: ✭ 20 (-28.57%)
Mutual labels:  cheatsheet

TypeScript Cheatsheet

Cheatsheet for TypeScript. Please make an issue if you encounter a problem and PR always welcome.

Table of Contents

Expand Table of Contents

Section 1: Setup

  1. Go to TypeScript download from there or just type npm install -g typescript.
  2. Check the installed version tsc -v.

Section 2: Data Types

String, Number, Array, Boolean

There are some basic types available for TypeScript. Such as string, number, Array<number>, string[], boolean etc. We can do Type Declaration by them.

let x: number = 5;
let name: string = "John Doe";
let showErrorMsg: boolean = true;
let numbers: number[] = [1, 2, 3];
let numbers: Array<number> = [1, 2, 3];
let students: Array<string> = ["John Doe", "Michael"];

function showDetail(name: string, age: number): void {
  console.log(name);
}

Tuples

This is something new in TypeScript 3. A Tuple is an array but the number of elements are fixed.

let product: [string, number];
product = ["John", 10];

let val: [string, ...number[]];
val = ["John", 5, 7, 9];

Enum

Enum allows us to declare a set of collection in which we can assign them a perticular value such number, string by default TS compiler will assign them in number.

enum ProgrammingLanguage {
  javascript,
  python,
  php,
}

// This will be changed as

enum ProgrammingLanguage {
  javascript = 0,
  python = 1,
  php = 2,
}

Union

TypeScript allows us to assign more than one data type for a variable or for a function.

let address: string | number;
address = "New York";
// or
address = 3100;

function getValue(): string | number {
  return "John Doe";
  // or
  return 123;
}

Any

If you don't know the actual data type or you don't want to assign a data type you can use any.

let detail: any;
detail = "Developer";

function getValue(): any {
  return "Developer";
}

Unknown

unknown is the type-safe counterpart of any. Anything is assignable to unknown, but unknown isn’t assignable to anything but itself.

let value: unknown;

value.trim(); // Error
value(); // Error
new value(); // Error

Void

This is useful when you are not returning anything from the function(this is not mandatory to include).

function getError(): void {
  console.log("TypeScript is a SuperSet of JavaScript");
}

Never

Use never when a function doesn't return anything. This can be used when a function returns error.

function error(message: string): never {
  throw new Error(message);
}

Partial

Partial makes all properties of the type optional.

interface User {
  id: number;
  name: string;
  email: string;
}

let user: Partial<User> = {
  id: 1,
};

Readonly

When we use readonly, we can’t assign them with other variables, can’t update or delete. This avoids unexpected mutation.

let students: readonly Array<string> = ["John", "Michael", "Adam"];

Pick

It allows you to create a new type from an existing interface.

interface User {
  id: number
  name: string
  email: string
}

function foo(args: Pick<User, "name" | "email">) {
  console.log(args);
}

foo({ name: "John Doe", email: "[email protected]" });

Section 3: Interface

An Interface is a group of properties and methods that describe an object but neither does initialization nor implementation.

interface User {
  name: string;
  age: number;
  getPoints(point: number): number;
}

let user: User = {
  name: "John Doe",
  age: 25,
  getPoints(point: number): number {
    return point * point;
  },
};

We can make properties and parameters optional.

interface User {
  name?: string;
  age: number;
  getPoints(point?: number): number;
}

let user: User = {
  age: 25,
  getPoints(): number {
    return 5 * 5;
  },
};

Section 4: Type Alias

Type Alias creates a new name for a type.

type GetArea = (width: number, height: number) => number;

interface Rectangle {
  getArea: GetArea;
}

let rectangle: Rectangle = {
  getArea(width: number, height: number): number {
    return width * height;
  },
};

Section 5: Class

Just like the other language TypeScript has a class feature.

class Product {
  name: string;
  price: number;

  constructor(name: string, price: number) {
    this.name = name;
    this.price = price;
  }

  getTotalPrice(discount: number): number {
    return this.price - discount;
  }
}

const product = new Product("Milk", 250);

We can add interface for Product class.

interface IProduct {
  name: string;
  price: number;
  getTotalPrice(discount: number): number;
}

class Product implements IProduct {
  name: string;
  price: number;

  constructor(name: string, price: number) {
    this.name = name;
    this.price = price;
  }

  getTotalPrice(discount: number): number {
    return this.price - discount;
  }
}

const product = new Product("Milk", 250);

Section 6: Generics

We can specifically pass the type to any function but what if when we don't know the type to pass, Generic can help us.

// Generic Function
function removeItem<T>(arr: Array<T>, item: T): Array<T> {
  let index = arr.findIndex((i) => i === item);
  arr.splice(index, 1);
  return arr;
}

console.log(removeItem([1, 2, 3], 2));
console.log(removeItem(["John", "Michael"], "John"));
// Generic Class
class Country {
  protected countryName: string;

  constructor(countryName: string) {
    this.countryName = countryName;
  }

  getName() {
    return this.countryName;
  }
}

class Australia extends Country {}
class England extends Country {}

let australia = new Australia("Australia");
let england = new England("England");

function getName<T>(country: T): T {
  return country;
}

console.log(getName(australia));
console.log(getName(england));

Section 7: Symbol

Symbol is a primitive data type, which is also immutable and unique.

let sym1 = Symbol("key");
let sym2 = Symbol("key");

sym1 === sym2; // false

Section 8: Keyof & Indexed Access Types

In TypeScript keyof operator extracts the set of keys for a given type.

interface IUser {
  name: string;
  age: number;
}

type UserKeys = keyof IUser; // "name" | "age"

Using the keyof operator we can do Indexed Access Types. The key parameter can get the type of each key of obj.

function getValue<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const user = {
  id: 1,
  name: "John Doe",
};

console.log(getValue(user, "id")); // 1

Section 9: Mapped Types

In TypeScript Mapped Types allow us to create new types from existing types.

interface Person {
  name: string;
  age: number;
}

type readonlyPerson = {
  readonly [P in keyof Person]: Person[p];
};

Section 10: Type Guards

In order to find specific type when we use union types, we can use the Type Guard. typeof, instanceof, in are the examples of Type Guard.

// typeof
function showMessage(message: string | object): void {
  if (typeof message === "string") {
    console.log("The type is string");
  } else if (typeof message === "object") {
    console.log("The type is object");
  }
}

showMessage({ name: "John Doe" });
// instanceof
class User {
  id: number;
}

class Product {
  name: string;
}

function showMessage(message: User | Product): void {
  if (message instanceof User) {
    console.log("Message is an instance of User");
  } else if (message instanceof Product) {
    console.log("Message is an instance of Product");
  }
}

showMessage(new User());

Section 11 Namespaces

You might have come across the term namespace while working with TypeScript. And you might wonder what on earth is a namespace? We will be dealing with the basic concepts of namespaces and how we can use them to write efficient codes.

namespace AcmeCorp.Logging {
  export class Logger {
       static log(msg: string) : void {
        console.log(msg);
      };
  }
}

/// <reference path="AcmeCorp.Logging.ts" />

//Alias
import logger = AcmeCorp.Logging.Logger;

namespace AcmeCorp.OnlineStore {
  class OrderLogic {
    calcOrder(): number {
        logger.log("calculating order");
        return 0;
    }
  }
}
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].