Lesson 2 / 7

Basic Types and Type Inference

let age: number = 25;nlet name: string = "Tutoline";nlet isActive: boolean = true;nlet tags: string[] = ["python", "typescript"];nlet coordinates: [number, number] = [28.6, 77.2];   // a tuple: fixed length and types

Type inference

let age = 25;         // TypeScript infers this is a number, no annotation needednage = "twenty-five";  // Error: Type 'string' is not assignable to type 'number'

You rarely need to annotate every single variable — TypeScript infers the type from whatever value you assign, and still enforces it from that point on. Explicit annotations like : number matter most on function parameters, where there is no initial value for TypeScript to infer from.

The any type — and why to avoid it

let data: any = fetchSomething();   // opts out of type checking entirely for this value

any tells TypeScript to stop checking that value’s type altogether — it compiles, but you have silently given up every safety guarantee TypeScript was providing. Reach for any only as a genuine last resort; unknown (covered below) is almost always the safer choice when a value’s type truly cannot be known upfront.

Union types

function printId(id: number | string) {n    console.log(`ID: ${id}`);n}nnprintId(42);       // OKnprintId("abc123"); // also OKnprintId(true);     // Error

A union type (number | string) says a value can be one of several specific types — more precise, and safer, than falling back to any whenever a value could reasonably be more than one type.