Skip to content

Instantly share code, notes, and snippets.

@ivankisyov
Last active December 26, 2018 12:39
Show Gist options
  • Save ivankisyov/d0083e767f241ef19b943609a88cffb2 to your computer and use it in GitHub Desktop.
Save ivankisyov/d0083e767f241ef19b943609a88cffb2 to your computer and use it in GitHub Desktop.
Typescript

Typescript

Installation

Global installation

npm i -g typescript

Configuration

tsc -init
// if you run tsc in the terminal, all *.ts files will be compiled to normal *.js files

Types in TS

Tupples

let addresses: [string, number, string, number] = [
  "some street",
  55,
  "another street",
  5
];

Todo: Enum

Functions

Expect a string as an argument and the function returns a string

function returnString(text: string): string {
  return text;
}

No explicit return

function sayHi(): void {
  console.log("hi");
}

Type function

// expect multiply be a fn which takes 2 arguments of type number
// and that fn must return a number
let multiply: (num1: number, num2: number) => number;

Default argument's value

function countDown(start: number = 10): void {
  while (start > 0) {
    console.log(start);
    start--;
  }
}

countDown();

Objects

let user: { name: string; age: number; isClient: boolean } = {
  name: "smith",
  age: 11,
  isClient: false
};

Create new type

type Address = { street: string; streetNumber: number };

let userAddress: Address = {
  street: "some street",
  streetNumber: 11
};

// create your own types
type team = {
  team: string;
  draws: number;
  wins: number;
  lost: number;
};

type Scores = object[];
// endOf: create your own types

let muInfo: team = {
  team: "MU",
  wins: 11,
  lost: 3,
  draws: 11
};

let premierLeagueTeams: Scores = [muInfo];

Union Type

let age: string | number;
age = 11;
age = "11";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment