Lesson 4 of 20

Basic Types

Primitive Types

TypeScript includes all JavaScript primitive types plus a few additional ones for better type safety.

Example
// string, number, boolean
let firstName: string = "John";
let score: number = 95.5;
let passed: boolean = true;

// null and undefined
let empty: null = null;
let notDefined: undefined = undefined;

// any — opt out of type checking (avoid when possible)
let flexible: any = "hello";
flexible = 42;  // No error

// unknown — safer alternative to any
let input: unknown = "hello";
// input.toUpperCase(); // Error! Must check type first
if (typeof input === "string") {
  input.toUpperCase(); // OK after type check
}

Special Types

TypeScript has several special types: void, never, any, and unknown. Each serves a specific purpose.

Example
// void — function returns nothing
function logError(msg: string): void {
  console.error(msg);
}

// never — function never returns (throws or infinite loop)
function throwError(msg: string): never {
  throw new Error(msg);
}

// Literal types — exact values
let direction: "north" | "south" | "east" | "west";
direction = "north"; // OK
direction = "up";    // Error

Type Assertions

Sometimes you know more about a type than TypeScript does. Type assertions let you tell the compiler to treat a value as a specific type.

Example
// Type assertion with 'as'
let value: unknown = "Hello World";
let length: number = (value as string).length;

// Angle bracket syntax (not in JSX/TSX files)
let len: number = (<string>value).length;

// DOM example
const input = document.getElementById("email") as HTMLInputElement;
input.value = "user@example.com";