← TypeScript EnglishChapter 02 of 12

Variables and Types

## Learning Objectives - Declare variables with let, const, and var - Understand TypeScript basic types - Master type inference - Learn type annotations - Work with arrays and tuples ## Variable Declarations ### let Block-scoped, mutable variable: ```typescript let age: number = 25; age = 26; // OK ``` ### const Block-scoped, immutable binding: ```typescript const PI: number = 3.14159; // PI = 3.14; // Error: Cannot assign to 'PI' ``` ### var (Avoid) Function-scoped, hoisted (avoid in TypeScript): ```typescript var name: string = "John"; // Prefer let and const ``` ## Basic Types ### number All numbers, integers and decimals: ```typescript let integer: number = 42; let decimal: number = 3.14; let hex: number = 0xFF; let binary: number = 0b1010; let octal: number = 0o744; ``` ### string Text values: ```typescript let firstName: string = "John"; let lastName: string = 'Doe'; let fullName: string = `${firstName} ${lastName}`; // Template literals let greeting: string = `Hello, ${firstName}!`; ``` ### boolean True or false: ```typescript let isActive: boolean = true; let isComplete: boolean = false; ``` ### null and undefined ```typescript let nullValue: null = null; let undefinedValue: undefined = undefined; ``` ## Type Inference TypeScript can infer types from initial values: ```typescript // Type is inferred as 'string' let message = "Hello"; message = 123; // Error: Type 'number' is not assignable to type 'string' // Type is inferred as 'number' let count = 10; count = "ten"; // Error ``` ### When Inference Works ```typescript let x = 10; // number let y = "hello"; // string let z = true; // boolean ``` ## Type Annotations Explicit type declarations: ```typescript let age: number; let name: string; let active: boolean; // With initialization let score: number = 100; let title: string = "Developer"; ``` ## Arrays ### Type Annotation ```typescript let numbers: number[] = [1, 2, 3, 4, 5]; let names: string[] = ["Alice", "Bob", "Charlie"]; let flags: boolean[] = [true, false, true]; ``` ### Generic Array Syntax ```typescript let numbers: Array = [1, 2, 3]; let names: Array = ["Alice", "Bob"]; ``` ### Accessing Elements ```typescript let first: number = numbers[0]; let last: string = names[names.length - 1]; ``` ## Tuples Fixed-length arrays with known types: ```typescript let person: [string, number]; person = ["Alice", 30]; // person = [30, "Alice"]; // Error: Type 'number' is not assignable to type 'string' let name: string = person[0]; let age: number = person[1]; ``` ### Optional Elements ```typescript let config: [string, number?]; config = ["development"]; config = ["development", 8080]; ``` ## Any Type Bypass type checking (avoid when possible): ```typescript let dynamic: any = 123; dynamic = "hello"; dynamic = true; dynamic = [1, 2, 3]; // No type checking on any dynamic.toUpperCase(); // Works at compile time ``` ## Unknown Type Type-safe alternative to any: ```typescript let unknownValue: unknown = 123; // Must narrow or check before use if (typeof unknownValue === "string") { console.log(unknownValue.toUpperCase()); } // Or use type assertion let str: string = unknownValue as string; ``` ## Void Type No return value: ```typescript function logMessage(message: string): void { console.log(message); // No return statement } let result: void = undefined; ``` ## Never Type Function that never returns: ```typescript function throwError(message: string): never { throw new Error(message); } function infiniteLoop(): never { while (true) { // Never returns } } ``` ## Type Assertions Tell TypeScript the type: ```typescript let value: unknown = "hello"; // Angle bracket syntax let len1: number = (value).length; // as syntax let len2: number = (value as string).length; ``` ## Object Types ```typescript let point: { x: number; y: number } = { x: 10, y: 20 }; function distance(p1: { x: number; y: number }): number { return Math.sqrt(p1.x ** 2 + p1.y ** 2); } ``` ## Union Types Multiple possible types: ```typescript let id: string | number; id = 123; id = "ABC123"; function printId(id: string | number): void { console.log(`ID: ${id}`); } ``` ## Type Aliases Name for a type: ```typescript type StringOrNumber = string | number; type Point = { x: number; y: number }; let value: StringOrNumber = "hello"; let coord: Point = { x: 0, y: 0 }; ``` ## readonly Properties Cannot be modified after creation: ```typescript interface Config { readonly host: string; readonly port: number; } let config: Config = { host: "localhost", port: 8080 }; // config.port = 3000; // Error: Cannot assign to 'port' ``` ## Summary - Use `const` by default, `let` when needed, avoid `var` - Basic types: `number`, `string`, `boolean`, `null`, `undefined` - TypeScript infers types from initial values - Arrays: `number[]` or `Array` - Tuples: `[string, number]` for fixed-length arrays - Avoid `any`, prefer `unknown` - Use type aliases for complex types - `readonly` for immutable properties

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →