Types

any
void

boolean
number
string

null
undefined


// or Array<string> 
string[]  

[string, number]

// union
string | null | undefined

// unreachable
never 

Declarations

let isDone: boolean
let isDone: boolean = false

function add (a: number, b: number): number {
  return a + b
}

// Return type is optional
function add (a: number, b: number) { ... }

Type assertions

Variables

let len: number = (input as string).length
// not allowed in JSX
let len: number = (<string> input).length

Functions

function func(this: {a: number, b: number}, a: number, b: number) {
  this.a = a;
  this.b = b;
  return this;
}

Interfaces

Inline

function a (person: { name: string }) {
  console.log(person.name)
}

// Note the semicolon
function getUser (): { name: string; age?: number } {}

Explicit

interface LabelOptions {
  label: string,
  // optional
  age?: number,
  // readonly
  readonly name: string
}

function printLabel(options: LabelOptions) {}

Classes

class Point {
  x: number
  y: number
  static instances = 0
  constructor(x: number, y: number) {
    this.x = x
    this.y = y
  }
}