← Back to libraryQuestion 210 of 468
🔷TypeScriptBeginner

Basic Types and Type Annotations

📌 Definition:

TypeScript's primitive types include string, number, boolean, null, undefined, and symbol, plus array (T[] or Array<T>), tuple ([string, number]), object, any, unknown, void, and never.

📖 Detailed Explanation:

You annotate a variable with a colon: let name: string = 'qa'. Arrays are number[] or Array<number>; tuples fix length and per-position types ([string, number] for a [name, age] pair). object is a non-primitive. any opts out of type checking (avoid it), unknown is a safe any that must be narrowed before use, void is the return type of functions that return nothing, and never is for functions that never return (throw/infinite). Annotations are often optional because TypeScript infers types, but they document intent and constrain reassignment.

🔑 Key Points:
  • Primitives: string, number, boolean, null, undefined, symbol
  • Arrays T[]/Array<T>; tuples [string, number] fix position types
  • any disables checking; unknown is a safe any (must narrow)
  • void = returns nothing; never = never returns
🌍 Real-World Example:

Typing an API response tuple from a helper: function status(): [number, string] { return [200, 'OK']; } — callers know position 0 is a number code and position 1 a string message.

🎯 Scenario-Based Interview Question:

What's the difference between typing a variable as any versus unknown?