Warning, technical post alert.

I have been programming in the last two weeks, and boy do I miss it. We have been using a variant of CoffeeScript, known as iced-coffeescript. It is like Coffeescript, which is like Javascript, but it is also like Python with tabs instead of brackets. But as we add more programmers to the team, the product team has prioritized type safety so an entire class of type-related bugs can be eliminated. So, the use of TypeScript in all frontend projects is now enforced.

In my hour-long journey, I wrote notes to aid with the learning process. This is a copy of my notes, verbatim. Assuming you are already familiar with javascript, you will have learnt TypeScript after you are done reading my notes.


Learning Typescript

This document will serve as a personal journal in learning Typescript.

Documentation

I am starting with TypeScript in 5 minutes, then moving onto the full docs.

Typescript

Type annotations in function parameters

By annotating varName: type. For example:

function bla(varName: string) {}

Using let to assign variables

To initialize a var, use let keyword.

```let water = "holy";`

Objects can have interfaces

Objects (like dictionaries in Python) that are embraced within curly brackets like {} can have predefined shapes and keywords with the interface keyword.

interface Singapore {
    isDictatorship: boolean;
}

Classes

Historically, classes do not exist in Javascript. Instead, Javascript uses prototype.

With Typescript, classes are back.

class Student {
    someClassVar: string;
    isExpelled: boolean;
    
    constructor(public someVarOne: string, public firstName: string) {
        this.isExpelled = true;
    }
}

When you init a variable, you can give annotate a type

let isDone: boolean = false;

These is a non-exhuastive list of basic types

  • string
  • boolean
  • number -- floating point
  • string[] array -- can be any type
  • [string, string] -- tuple; an array with a fixed number of elements
  • any - generics
  • void
  • undefined
  • null
  • never - return type for function that never returns (ie: throws exception)
  • object - generic/looser version of a tuples

There is Enum support in TypeScript

It is enabled with Enum keyword.

enum Color {Red, Green, Blue}

Enum can be annotated as a type.

Annotating function return type

function error(): void {}

Injecting type annotations

Sometimes you’ll end up in a situation where you’ll know more about a value than TypeScript does. Usually this will happen when you know the type of some entity could be more specific than its current type.

let strLength: number = (<string>someValue).length;

That was easy.