TypeScript provides a set of primitive types that form the foundation for building type-safe applications. Knowing these types helps you write cleaner, more predictable code.
List of Primitive Types in TypeScript
-
string: Represents textual data.
- Example:
let name: string = "Alice";
- Example:
-
number: For all numbers, including integers and floats.
- Example:
let age: number = 30;
- Example:
-
boolean: Represents true or false values.
- Example:
let isActive: boolean = true;
- Example:
-
null: Indicates the intentional absence of any value.
- Example:
let data: null = null;
- Example:
-
undefined: Represents an uninitialized variable.
- Example:
let count: undefined = undefined;
- Example:
-
symbol: Used to create unique identifiers (ES6+ feature).
- Example:
let id: symbol = Symbol('id');
- Example:
-
bigint: For working with large integers beyond the safe integer limit for numbers (ES2020+ feature).
- Example:
let bigNumber: bigint = 9007199254740991n;
- Example:
Why Use Primitive Types?
- They ensure type safety
- Help prevent runtime errors
- Make your code self-documenting
Example Usage
let title: string = "TypeScript";
let year: number = 2024;
let enrolled: boolean = false;
Understanding and using these primitive types is a core part of writing robust TypeScript code.
Top comments (0)