DEV Community

Cover image for The TypeScript Cheat Sheet: Your Essential Guide to Type Safety
Muhammad Zain Afzal
Muhammad Zain Afzal

Posted on

The TypeScript Cheat Sheet: Your Essential Guide to Type Safety

Introduction:

TypeScript has revolutionized JavaScript development by adding static typing, making our code more robust and maintainable. This cheat sheet provides a quick reference to the most essential TypeScript features, helping you write cleaner, more reliable code with ease. Whether you're new to TypeScript or looking for a refresher, this guide is designed to be your go-to resource.

Sections:

  1. Basic Types:

    • Description: The fundamental building blocks of type systems.
    • Code Snippets:

      // Basic Types
      let age: number = 30;
      let name: string = "Alice";
      let isStudent: boolean = true;
      let id: null = null;
      let something: undefined = undefined;
      
*   **Explanation:** TypeScript infers the types if not explicitly declared, but explicit annotation enhances code readability.
*   **Use Cases:** Defining primitive values such as numbers, text, and boolean flags.
Enter fullscreen mode Exit fullscreen mode
  1. Arrays & Tuples:

    • Description: Working with ordered collections of data.
    • Code Snippets:

      // Arrays
      let numbers: number[] = [1, 2, 3, 4, 5];
      let strings: string[] = ["apple", "banana", "cherry"];
      let mixed: (string | number)[] = ["hello", 123, "world", 456]; // Union type
      
      // Tuples
      let person: [string, number] = ["John", 28]; // Fixed length and types
      
*   **Explanation:**  Arrays can have a single type or a union of types. Tuples are fixed-size arrays where each position has a specific type.
*   **Use Cases:**  Storing lists of similar items or structured data with fixed elements.
Enter fullscreen mode Exit fullscreen mode
  1. Objects & Interfaces:

    • Description: Defining the shape and structure of objects.
    • Code Snippets:

      // Interfaces
      interface Product {
        name: string;
        price: number;
        isAvailable?: boolean; // Optional property
      }
      
      // Using interfaces with objects
      let laptop: Product = { name: "Laptop", price: 1200, isAvailable: true };
      let book: Product = { name: "Book", price: 20 };
      
      // Type Alias
      type Coordinate = { x: number; y: number};
      let point: Coordinate = {x: 10, y: 20};
      
*   **Explanation:** Interfaces define a contract that objects must adhere to. Type Aliases allow you to give a name to any type in typescript. Optional properties use the `?` symbol.
*   **Use Cases:** Enforcing the structure of data passed between different parts of your code.
Enter fullscreen mode Exit fullscreen mode
  1. Functions:

    • Description: Adding type safety to function parameters and return values.
    • Code Snippets:

      // Function declarations with type annotations
      function add(a: number, b: number): number {
        return a + b;
      }
      
      // Arrow function with type annotations
      const multiply = (x: number, y: number): number => x * y;
      
      // Function with no return (void)
      function logMessage(message: string): void {
        console.log(message);
      }
      
      // Function with optional parameter
      function greet(name:string, greeting?: string): string {
        return greeting ? `${greeting}, ${name}!` : `Hello, ${name}!`;
      }
      
      greet('Alice');
      greet('Bob', 'Good Morning');
      
*   **Explanation:** TypeScript enforces parameter and return types, making your functions more reliable.
*   **Use Cases:** Catching type-related errors in your logic early on.
Enter fullscreen mode Exit fullscreen mode
  1. Unions & Intersections:

    • Description: Combining types to represent complex data structures.
    • Code Snippets:

      // Union Types
      type Status = "active" | "inactive" | "pending";
      let userStatus: Status = "active";
      
       type stringOrNumber = string | number;
       let mixedValue: stringOrNumber = 100;
       mixedValue = "hello";
      

    //Intersection Types
    type User = { name: string; id: number };
    type Employee = { department: string; role: string };

     type UserEmployee = User & Employee;
    
     const employee: UserEmployee = {
       name: "John",
       id: 123,
       department: "Sales",
       role: "Manager",
    };
    ```
    
*   **Explanation:** Union types allow a variable to hold multiple types. Intersection combines several types into one.
*   **Use Cases:** Handling data that can come in different formats or merging types into a single structure.
Enter fullscreen mode Exit fullscreen mode
  1. Enums:

    • Description: Defining a set of named constants.
    • Code Snippets:

      enum Direction {
        Up = 1,
        Down,
        Left,
        Right,
      }
      
      let move: Direction = Direction.Right;
      
*   **Explanation:** Enums assign human-readable names to numeric values, increasing code clarity.
*   **Use Cases:** Representing states, options, or flags in your application.
Enter fullscreen mode Exit fullscreen mode
  1. Generics:

    • Description: Creating reusable components that can work with different types.
    • Code Snippets:

      // Generic Function
      function identity<T>(arg: T): T {
        return arg;
      }
      
      let myIdentityString = identity<string>("hello");
      let myIdentityNumber = identity<number>(10);
      
      // Generic Interface
      interface Box<T> {
         value: T;
      }
      
      let stringBox: Box<string> = {value: "My String"}
      
*   **Explanation:** Generics enable the creation of components that work with a variety of types without sacrificing type safety.
*   **Use Cases:** Creating reusable data structures and algorithms that aren't tied to specific types.
Enter fullscreen mode Exit fullscreen mode

Conclusion:

This cheat sheet is a starting point for your TypeScript journey. Mastering these core concepts will make your development process smoother and more efficient. As you gain experience, you'll explore more advanced features like decorators and modules, further enhancing your TypeScript skills. Keep practicing and experimenting to see the full power of this remarkable language.

Top comments (0)