Basic Types
TypeScript Type System•Section 2 of 4•beginner
Topic Overview
Take your time to understand each concept. Practice with the examples below!
TypeScript has a rich type system with many different types to choose from. Let's explore each one with real-world examples!
Primitive Types - The Building Blocks:
- •string:Text data like names, messages, or any text
- •number:All numbers - integers, decimals, negative numbers
- •boolean:True or false values for yes/no decisions
- •symbol:Unique identifiers (advanced use)
- •bigint:Really large numbers (beyond regular number limits)
Arrays - Lists of Things:
- •Basic array:number[] for a list of numbers
- •Alternative syntax:Array<string> for a list of strings
- •Mixed arrays:(string | number)[] can contain both
- •Readonly arrays:readonly string[] can't be modified
Tuples - Fixed-Length Arrays:
Think of tuples as a shopping list where order and count matter:
- •Coordinates:[x: number, y: number]
- •User info:[name: string, age: number, isActive: boolean]
- •Fixed length and types in specific positions
Enums - Named Constants:
Perfect for a fixed set of values like days of the week or user roles:
- •Numeric enums:enum Days { Monday, Tuesday, Wednesday }
- •String enums:enum Colors { Red = "RED", Blue = "BLUE" }
- •Makes code more readable and prevents typos
Special Types:
- •any:The escape hatch - accepts any type (use sparingly!)
- •unknown:Safer than any - must check type before use
- •void:Functions that don't return anything
- •never:Functions that never return (throw errors or infinite loops)
- •null and undefined:Absence of value
Object Types:
- •Basic objects:{ name: string; age: number }
- •Optional properties:{ name: string; age?: number }
- •Index signatures:{ [key: string]: any } for dynamic keys
Example
// Primitive Typeslet message: string = "Hello TypeScript";let count: number = 42;let pi: number = 3.14159;let isComplete: boolean = true;// Arrayslet numbers: number[] = [1, 2, 3, 4, 5];let colors: Array<string> = ["red", "green", "blue"];let mixed: (string | number)[] = ["Alice", 25, "Bob", 30];// Tuples - fixed length arrays with specific typeslet person: [string, number] = ["Alice", 30];let coordinate: [number, number, number] = [10, 20, 30];// Enumsenum Direction { Up = "UP", Down = "DOWN", Left = "LEFT", Right = "RIGHT"}enum StatusCode { Success = 200, NotFound = 404, ServerError = 500}let userDirection: Direction = Direction.Up;let responseStatus: StatusCode = StatusCode.Success;// Special typeslet uncertain: any = "could be anything";let nothing: void = undefined;let empty: null = null;let notDefined: undefined = undefined;console.log(`Direction: ${userDirection}, Status: ${responseStatus}`);