Skip to content

TypeScript leverages the foundational data types from JavaScript while introducing additional offerings to enhance type safety and code clarity. This section delves into these fundamental types, emphasizing the importance of type annotations.

Core Data Types:

  1. Primitive Types:
    • number: Represents numerical values (integers and decimals).
    • string: Represents sequences of characters (enclosed in quotes).
    • boolean: Represents true or false values.
    • symbol: A unique and immutable identifier (primarily for object properties).
    • undefined: Represents the absence of a value assignment.
    • null: Represents the intentional absence of a value.
  2. Additional Types:
    • void: Represents the absence of a return value from a function.
    • never: Represents a type that never occurs (used in exhaustive type checking).

Type Annotations:

While TypeScript often infers types automatically, explicitly declaring types using annotations is highly recommended. This practice:

  • Enhances Code Readability: Makes code easier to understand for developers by clearly indicating the intended data types.
  • Improves Maintainability: Simplifies code maintenance by making it easier to identify potential type-related issues.
  • Promotes Early Error Detection: Helps catch errors during development, preventing unexpected behavior in the application.

Example:

TypeScript

let age: number = 30; // Explicitly define 'age' as a number
let name: string = "Alice";

Type Inference:

Although type annotations are encouraged, TypeScript can infer types based on the assigned value:

TypeScript

let message = "Hello, world!"; // Type inferred as string
let isLoggedIn = true; // Type inferred as boolean

Key Takeaways:

  • Grasping fundamental types is crucial for effective TypeScript usage.
  • Explicit type annotations significantly enhance code quality and maintainability.
  • While type inference exists, explicit annotations are generally preferred.

Further Exploration:

TypeScript offers additional composite data types like arrays, tuples, and objects, which will be covered in subsequent sections. Explore the official TypeScript documentation and online resources for in-depth information on specific types and their usage.