myHotTake

Tag: TypeScript basics

  • How Do keyof and typeof Work in TypeScript?

    Hey there! If you find this story helpful, feel free to give it a like or share!


    So, I’m at a candy store. In this shop, there are two fascinating tools I can use: a special map and a magic lens. Let’s say keyof is my candy map. This map shows me all the different sections of the store, with each section labeled by the type of candy it holds. If I want to know what types of candies are available, I just look at my map. It tells me, “Oh, here are the lollipop section, the chocolate section, and the gummy bear section.” In TypeScript, keyof works similarly by giving me a list of keys from an object type, like identifying sections in my candy store.

    Now, let’s talk about typeof, which is my magic lens. This lens lets me peek into any candy jar and see what’s inside. If I point it at a jar, it tells me the exact type of candy it contains, like whether it’s a lollipop or a chocolate. In the world of TypeScript, typeof allows me to determine the type of a value or variable, just like peering into the jar to see what kind of candy I’m dealing with.

    So, while my candy map (keyof) helps me understand the categories available in the store, my magic lens (typeof) lets me see the specific candy types inside each jar. Both are essential for navigating this delightful store efficiently!

    If you enjoyed this sweet analogy, don’t hesitate to share it with others who might appreciate a tasty take on TypeScript concepts! 🍬


    Example: keyof

    I have a candy store inventory object:

    type CandyStore = {
      lollipops: number;
      chocolates: number;
      gummyBears: number;
    };
    
    // Using keyof to get the keys of the CandyStore type
    type CandyTypes = keyof CandyStore; 
    // CandyTypes is now "lollipops" | "chocolates" | "gummyBears"

    In this code, keyof CandyStore is like using my candy map, which shows me all the sections of the store, i.e., the keys of the CandyStore type.

    Example: typeof

    Now, suppose I have a specific candy jar:

    const myCandyJar = {
      flavor: "strawberry",
      type: "lollipop",
      quantity: 10,
    };
    
    // Using typeof to get the type of myCandyJar
    type JarType = typeof myCandyJar;
    // JarType is now { flavor: string; type: string; quantity: number; }

    Here, typeof myCandyJar acts like my magic lens, allowing me to see what’s inside the jar by determining the type of myCandyJar.

    Key Takeaways

    1. keyof: Just like a map in a candy store, keyof provides a list of keys (or sections) available in a TypeScript object type. It’s useful for understanding the structure of an object type by listing its keys.
    2. typeof: Similar to a magic lens, typeof lets you inspect the type of a specific value or variable. It’s handy for determining what types of data you’re working with at any given moment.