Data Types

TypeScript adds static type annotations to JavaScript variables and functions.

Basic Types

let name: string = 'Alice'
let age: number = 25
let isStudent: boolean = true
let nothing: null = null
let undef: undefined = undefined

// Any (avoid when possible!)
let anything: any = 42
anything = 'now a string'  // OK with any

Arrays

let numbers: number[] = [1, 2, 3]
let names: string[] = ['Alice', 'Bob']
let mixed: (string | number)[] = [1, 'two', 3]

// Generic syntax
let items: Array<string> = ['a', 'b', 'c']

Union Types

let id: string | number = 123
id = 'ABC'  // also OK

Type Aliases

type ID = string | number
type Point = { x: number; y: number }

let userId: ID = 42
let origin: Point = { x: 0, y: 0 }

Tuple

let pair: [string, number] = ['Alice', 25]
let [pName, pAge] = pair

Enum

enum Direction {
  Up = 'UP',
  Down = 'DOWN',
  Left = 'LEFT',
  Right = 'RIGHT'
}

const move = (dir: Direction) => console.log(dir)
move(Direction.Up)  // 'UP'