The Core Type System

The foundation of TypeScript is its ability to define the Type of data a variable or constant can hold. This prevents logical errors where an application might try to treat a string like a number or an object like an array.


1. Type Annotations

A type annotation explicitly tells the compiler what type a variable should be.

let username: string = "alice";
let count: number = 42;
let isActive: boolean = true;

2. Type Inference

TypeScript is intelligent. If you initialize a variable with a value, the compiler will Infer the type for you. You don't always need to write explicit annotations.

let score = 100; // TypeScript infers 'number'
// score = "high"; // Error: Type 'string' is not assignable to type 'number'

Best Practice: Rely on inference for simple variables; use explicit annotations for function parameters and complex return types.


3. Arrays and Tuples

I. Arrays

You can define arrays of a specific type.

let list: number[] = [1, 2, 3];
let names: Array<string> = ["Alice", "Bob"]; // Generic syntax

II. Tuples

A tuple is a fixed-length array where each element has a Specific Type at a Specific Position. This is commonly used for data pairs like GPS coordinates or state management hooks.

let contact: [string, number];
contact = ["Alice", 123456]; // Works
// contact = [123456, "Alice"]; // Error: Type mismatch at positions 0 and 1

4. Enums: Named Constants

Enums allow a developer to define a set of named constants. This makes it easier to document intent and creates a set of distinct cases.

enum TaskStatus {
    Todo,
    InProgress,
    Done
}

let current: TaskStatus = TaskStatus.Todo;

Interview Pro-Tips: Type Inference vs. Explicit

If an interviewer asks when to use which:


Technical Summary

  1. Safety: Prevents runtime type errors.
  2. Tuples: Fixed-shape arrays for structured data.
  3. Enums: Improving code readability by using semantic names for numeric/string states.