TypeScript Fundamentals
Type Annotations — Primitives
Master primitive type annotations in TypeScript including string, number, boolean, null, undefined, bigint, and symbol, along with strict null checking rules.
In TypeScript, Type Annotations allow developers to explicitly state what type of value a variable, function parameter, or return value is allowed to hold.
1. The Core Primitive Types
JavaScript has seven primitive types. TypeScript provides direct type annotations for all of them:
2. Basic Primitive Annotations
Numbers and BigInt
Strings
Booleans
3. null and undefined in TypeScript
By default in JavaScript, null and undefined represent empty states. In TypeScript, their behavior depends heavily on the "strictNullChecks" compiler option.
Strict Null Checking (strictNullChecks: true)
When strictNullChecks is enabled (recommended), null and undefined are not implicitly assignable to other types like number or string.
4. symbol Primitive
Symbols guarantee unique identifiers across object keys:
5. Interactive Code Playground
Test primitive type enforcement below:
6. Common Pitfalls & Edge Cases
String, Number, Boolean (capitalized wrappers). Always use lowercased primitives (string, number, boolean).any on Uninitialized Variables: Declaring let x; without an initializer or annotation results in x being implicitly assigned type any. Always annotate if uninitialized.7. Interview Q&A & Quizzes
& QuizQ1: What is the difference between null and undefined in TypeScript?
Answer:
undefined: Means a variable has been declared but has not yet been assigned a value.null: Represents an intentional, explicit assignment of "no value" or an empty reference.Q2: Why should you avoid new String("hello") in TypeScript?
Answer: new String("hello") creates an Object wrapper around the primitive string value. Objects fail assignment checks against the primitive string type in TypeScript and add unnecessary memory overhead.
8. Primitives Summary Table
| Primitive Type | Example Value | Description |
|---|---|---|
number | 42, 3.14, NaN | All numeric values (IEEE 754 floating point) |
string | "hello", 'world' | Textual data |
boolean | true, false | Logical truth values |
bigint | 100n | Large integers exceeding 2^53-1 |
symbol | Symbol("key") | Unique, immutable primitive identifier |
null | null | Explicit intentional empty value |
undefined | undefined | Default value of uninitialized variables |