TSTypeScript · Lesson 2 of 10

Basic Types

TypeScript has all JavaScript's types plus a few extras: tuples, enums, `unknown`, `never`, and `void`. The most important one is the one TypeScript infers for you automatically.

TypeScript
// Primitive types
let name: string      = "Alice"
let age: number       = 30
let active: boolean   = true
let nothing: null     = null
let missing: undefined = undefined

// Type inference — TypeScript infers from assignment, annotation often optional
let inferredName = "Bob"      // TypeScript knows this is string
let inferredAge  = 25         // TypeScript knows this is number
// inferredAge = "twenty-five"  // Error: Type 'string' is not assignable to 'number'

// Arrays
let nums: number[]         = [1, 2, 3]
let strs: Array<string>    = ["a", "b", "c"]  // generic form
let mixed: (string|number)[] = ["a", 1, "b", 2]

// Tuples — fixed-length array with known types at each position
let point: [number, number]           = [10, 20]
let entry: [string, number, boolean]  = ["Alice", 30, true]

const [x, y] = point   // destructuring works

// any — opt out of type checking (use sparingly)
let wild: any = "anything"
wild = 42
wild = true
wild.nonExistentMethod()  // no error — you lose type safety

// unknown — safer alternative to any (must narrow before use)
let input: unknown = getUserInput()
if (typeof input === "string") {
  console.log(input.toUpperCase())  // OK — narrowed to string
}

function getUserInput(): unknown { return "hello" }
TypeScript
// Enums — named constants
enum Direction {
  Up    = "UP",
  Down  = "DOWN",
  Left  = "LEFT",
  Right = "RIGHT",
}

function move(dir: Direction): void {
  console.log(`Moving ${dir}`)
}

move(Direction.Up)   // Moving UP
// move("UP")        // Error: string is not Direction

// Const enums — inlined at compile time, no runtime object
const enum Status {
  Pending,    // 0
  Active,     // 1
  Inactive,   // 2
}

// void — function returns nothing
function log(msg: string): void {
  console.log(msg)
}

// never — function never returns (throws or infinite loops)
function fail(msg: string): never {
  throw new Error(msg)
}

// Type assertions — tell TypeScript you know better
const input = document.getElementById("name") as HTMLInputElement
const value = (input).value
✦ Tip
Prefer `unknown` over `any`. With `any`, TypeScript stops checking entirely. With `unknown`, you must narrow the type before using it — which forces you to handle the case properly. Reserve `any` for genuinely untyped third-party data where you'll add types later.