T

Type System

TypeScript syntax guide

TypeScript type annotations and type system

Type System

TypeScript type annotations and type system

TypeScript type system (typescript)
        
          // Basic types
let name: string = "John";
let age: number = 25;
let isActive: boolean = true;
let data: any = "anything";
let unknown: unknown = "mystery";

// Arrays and tuples
let numbers: number[] = [1, 2, 3];
let tuple: [string, number] = ["hello", 42];

// Union types
let mixed: string | number = "hello";
mixed = 42; // OK

// Type aliases
type UserId = string | number;
type Point = {
  x: number;
  y: number;
};

// Interfaces
interface User {
  id: UserId;
  name: string;
  email?: string; // Optional property
  readonly createdAt: Date; // Read-only property
}

// Interface extending
interface Admin extends User {
  permissions: string[];
}

// Generic interface
interface ApiResponse<T> {
  data: T;
  status: number;
  message?: string;
}

// Usage
const user: User = {
  id: 1,
  name: "John",
  createdAt: new Date()
};

const admin: Admin = {
  id: "admin123",
  name: "Admin",
  createdAt: new Date(),
  permissions: ["read", "write", "delete"]
};

const response: ApiResponse<User[]> = {
  data: [user],
  status: 200
};
        
      

Explanation

TypeScript adds static typing to JavaScript with type annotations. It supports primitive types, complex types, generics, and interfaces for better code reliability.

Common Use Cases

  • Type safety
  • Better IDE support
  • Documentation
  • Refactoring confidence

Related TypeScript Syntax

Master Type System in TypeScript

Understanding type system is fundamental to writing clean and efficient TypeScript code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.

Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using type system effectively in your TypeScript projects.

Key Takeaways

  • Type safety
  • Better IDE support
  • Documentation