TypeScript's Building Blocks: Core Types

TypeScript's Building Blocks: Core Types in JavaScript: Before you can describe complex objects, you need the basic "colors" on TypeScript's palette.

Concept Explanation

Before you can describe complex objects, you need the basic "colors" on TypeScript's palette. Every value you annotate uses one of these primitive building blocks — and combining them is how you describe anything.

The magic character is the colon. After a variable name, : type tells TypeScript exactly what's allowed to live there.


Syntax or Core Structure

let age: number = 30;
let name: string = "Ada";
let isAdmin: boolean = true;

let scores: number[] = [90, 85, 100];      // an array of numbers
let pair: [string, number] = ["Ada", 30];  // a fixed tuple

let role: "admin" | "user" = "admin"; // literal union — only these two

Three special types you must know:

let anything: any;      // ❌ turns OFF type checking — avoid
let mystery: unknown;   // ✅ safe unknown — must check before use
function log(): void {} // returns nothing

Common Mistakes

  • Reaching for any: any silences the compiler entirely. Prefer unknown and narrow it.
  • Over-Annotating: let x: number = 5 is redundant — TS infers number. Annotate function params and return types; let inference handle the rest.
  • Confusing [] with tuple: number[] is any length; [number, number] is exactly two.

Best Practices

  • Let Inference Work: Annotate boundaries (function signatures), not every local variable.
  • Prefer Literal Unions: "sm" | "md" | "lg" beats a loose string for fixed options.
  • unknown over any: When a type is genuinely unknown, use unknown so TS forces you to check.

Practice Exercises

  1. The Palette: Declare one variable of each: number, string, boolean, and a string array.
  2. The Tuple: Create a tuple type Point of two numbers and assign one.
  3. The Union: Write type Size = "small" | "medium" | "large" and try assigning an invalid value to see the error.