Skip to main content

7) Typescript Utility Types

Updated Markdown
Part of seriesTypescript
  1. Partial<T>
    Makes all properties optional.

    import React, { useState } from "react";
    
    type User = {
      name: string;
      email: string;
      age: number;
    };
    
    export default function App() {
      const [user, setUser] = useState<User>({
        name: "Rahul",
        email: "rahul@test.com",
        age: 30,
      });
    
      const updateUser = (data: Partial<User>) => {
        setUser(prev => ({ ...prev, ...data }));
      };
    
      return (
        <button onClick={() => updateUser({ age: 31 })}>
          Update Age
        </button>
      );
    }
    

    Real-Time Usage
    i) Form updates
    ii) PATCH APIs
    iii) Redux partial state updates
    iv) Editable profile forms

  2. Pick<T, K>
    Creates a type by selecting specific properties.
    Passing only required props to components.

    type User = {
      id: number;
      name: string;
      email: string;
      password: string;
    };
    
    type ProfileProps = Pick<User, "name" | "email">;
    
    function Profile({ name, email }: ProfileProps) {
      return (
        <div>
          <h2>{name}</h2>
          <p>{email}</p>
        </div>
      );
    }
    

    Real-Time Usage
    i) API response shaping
    ii) Component props
    iii) Restricting sensitive fields
    iv) DTO creation

  3. Omit<T, K>
    Creates a type by removing specific properties.
    Prevent exposing sensitive fields.

    type User = {
      id: number;
      name: string;
      email: string;
      password: string;
    };
    
    type UserCardProps = Omit<User, "password">;
    
    function UserCard(props: UserCardProps) {
      return <div>{props.name}</div>;
    }
    

    Real-Time Usage
    i) Hide passwords/tokens
    ii) Public API types
    iii) Remove internal fields
    iv) Reusable UI-safe models

  4. Record<K, T>
    Creates an object type with dynamic keys.
    Dynamic UI configuration.

    type Theme = "light" | "dark";
    
    const themeStyles: Record<Theme, string> = {
      light: "bg-white text-black",
      dark: "bg-black text-white",
    };
    
    function App() {
      const currentTheme: Theme = "dark";
    
      return (
        <div className={themeStyles[currentTheme]}>
          Hello
        </div>
      );
    }
    

    Real-Time Usage
    i) Config maps
    ii) Enum-based objects
    iii) Translation dictionaries
    iv) Role-based access maps

  5. Required<T>
    Makes all properties mandatory.
    Ensure props are fully available.

    type Config = {
      apiUrl?: string;
      timeout?: number;
    };
    
    function initialize(config: Required<Config>) {
      console.log(config.apiUrl);
    }
    

    Real-Time Usage
    i) Final validated objects
    ii) Required config objects
    iii) Form submission validation

  6. Readonly<T>
    Makes all properties immutable.
    Prevent accidental mutation.

    type Props = Readonly<{
      title: string;
    }>;
    
    function Header(props: Props) {
      // props.title = "New"; ❌ Error
    
      return <h1>{props.title}</h1>;
    }
    

    Real-Time Usage
    i) Immutable Redux state
    ii) Prevent side effects
    iii) Safe props handling
    iv) Functional programming patterns

  7. Comparison Table
    i) Partial<T>
    Purpose: Make all properties optional
    Main Use Case: Update forms/state
    ii) Pick<T, K>
    Purpose: Select specific fields
    Main Use Case: Component props
    iii) Omit<T, K>
    Purpose: Remove specific fields
    Main Use Case: Hide sensitive data
    iv) Record<K, T>
    Purpose: Dynamic key-value object
    Main Use Case: Config maps
    v) Required<T>
    Purpose: Make all fields mandatory
    Main Use Case: Validation
    vi) Readonly<T>
    Purpose: Prevent mutation
    Main Use Case: Immutable state

No comments yet. Be the first to comment.