Skip to content

Instantly share code, notes, and snippets.

@liangti
Created October 3, 2019 22:57
Show Gist options
  • Select an option

  • Save liangti/4d8f269046603307230639214d076b60 to your computer and use it in GitHub Desktop.

Select an option

Save liangti/4d8f269046603307230639214d076b60 to your computer and use it in GitHub Desktop.

TypeScript

Feature

Basic Type

boolean

false and true.

let a: boolean = false;

number

let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;

string

let color: string = "blue";
color = 'red';

array

let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];

tuple

// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10]; // OK
// Initialize it incorrectly
x = [10, "hello"]; // Error

enum

enum Color {Red, Green, Blue}
let c: Color = Color.Green;

any

let isDone: any = false;
isDone.ifItExists()

Why we need any? Would not specifying any word works? No. If without any the compiler shows that ifItExists is not a method of isDone.

This is a kind of compatible design? To get people comfortable.

void

It's like the opposite of any, that the variable cannot have any type. Useful in function return value.

function warnUser(): void {
    console.log("This is my warning message");
}

let a: void = 1; //error
let a: void = undefined; //pass

undefined & null

These two are actually a type???

It's in advanced topic chapter.

never

Never be assigned.

let a:never;
a = 2; // wrong

It's useful in function return type

// Function returning never must have unreachable end point
function error(message: string): never {
    throw new Error(message);
}

object

Representing non-primitive type

Type Inference

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