Skip to content

Instantly share code, notes, and snippets.

@Aadv1k
Created March 3, 2022 05:03
Show Gist options
  • Save Aadv1k/f42d82294d15bf741e37b4353225b58a to your computer and use it in GitHub Desktop.
Save Aadv1k/f42d82294d15bf741e37b4353225b58a to your computer and use it in GitHub Desktop.
A simple typescript tutorial / reference cheat sheet

Typescript

Why?

  • Adds optional static types in JavaScript.
  • Makes the code more expressive.
  • Makes it easier to catch bugs in production.
  • Can translate to various ecmaScript version.

Usage

Setup

$ npm init -y
$ npm i -D typescript

in package.json add a dev script

"dev": "tsc --watch ."

Config

$ ./node_modules/.bin/tsc --init

this will initialize a tsconfig.json file with defaults and comments.

Syntax

Type declarations

let id: number = 5 
id = 'foo' 
// will yield an error in typescript as id is declared to be a number

Variables

let foo: string = 'hello world!';
let bar: boolean = false;
let x: any = 'blah' // can be anything

Arrays

let ages: number[] = [12, 15, 18];
let names: string[] = ['joe', 'john'];
let random: any[] = ['joe', 13.5, false, [1,2,3]]; // can be anything

Tuples allow you to specify types at positions in an array

let human: [string, number, boolean] = ['paul', 34, false];

Unions allows the developer to specify more than one type

let baz: string | number  = 23
let baz: string | number  = 'hello' // This is valid in an union

Enums starts a counter from the top most element

enum greet {
    hi,
    bye = 3,
    hello
}

greet.hi // returns 0
greet.hello // returns 4 because the element before it was set to 3 

Objects

type Animal = {
    name: string,
    age: number
}

const cat: Animal = {
    name: 'Pants',
    age: 3
}

Interfaces are similar to type except they cannot be used with unions.

// Allows optional types and readonly properties
interface Animal = {
    readonly species: string, // this can only be read after declaration
    name: string,
    age: number,
    sad?: boolean
}

const cat: Animal = {
    species: 'Ginger' 
    name: 'Pants',
    age: 3
}

cat.species = 'Something else' // will throw an error

Classes

class Animal {
    protected dna: number // this can only be accesed within the class 
    species?: string
    name: string

    constructor(species: string, name: string) {
        this.species = species,
        this.name = name,
    }

    info(): void {
        console.log(`${this.name} is doing fine`)
    }
}

Generics allow a more specific type over using any

function foo<T>(items: T[]): T[] {
    return [...items]
}

let names = foo<string>(['hello', 'world']) // more explicit than using any 
let ages = foo<number>([12, 13, 5, 6]) // more explicit than using any 

Type assertion

let anything: any = 2 
let foo = <number>anything // We assert that anything is a number

let bar = anything as number // This also works

Functions

// returns a string
function greet(name: string, age: number): string {
    return $`hello ${name}, you are ${age} years old`
}

// Does not return anything, thus "void"
function greetConsole(name: string, age: number): void {
    console.log($`hello ${name}, you are ${age} years old`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment