TypeScript中如何将typeof用于匿名类型?求实际应用场景
Hey there! Great question about typeof in TypeScript—it's one of those tools that feels a bit abstract when you first encounter it, but it becomes incredibly handy once you see it solving real-world problems. Let's walk through practical use cases, starting with the example you shared and expanding from there.
Your sample code is a perfect starting point: you're taking an existing object (rectangle1) and extracting its type to reuse elsewhere. This is ideal when you have a "template" object and want to ensure other variables/functions adhere to that exact shape without manually writing a type definition.
Here's how it plays out in a more complete scenario:
// Your original object let rectangle1 = { width: 100, height: 200 }; // Extract its type into a named type type Rectangle = typeof rectangle1; // Use the type to enforce shape in a function function calculateArea(rect: Rectangle): number { return rect.width * rect.height; } // Valid: matches the Rectangle shape const myDesk: Rectangle = { width: 120, height: 80 }; console.log(calculateArea(myDesk)); // 9600 // Invalid: TypeScript throws an error (missing "height") const badShape: Rectangle = { width: 50 };
Most projects use config objects to store environment settings, API URLs, or app preferences. typeof lets you turn these runtime objects into types, so you can update or reference config values without risking typos or invalid keys.
Example:
// Runtime config object const appConfig = { port: 3000, env: "development", apiBaseUrl: "/api/v2" }; // Extract the config's type type AppConfig = typeof appConfig; // A function that safely updates config (only accepts valid keys) function updateConfig(updates: Partial<AppConfig>): void { // Logic to merge updates into appConfig } // Valid update: uses a key that exists in AppConfig updateConfig({ port: 3001 }); // Invalid update: TypeScript flags "logLevel" as an unknown key updateConfig({ logLevel: "debug" });
Instead of manually writing the return type of a function, you can use typeof with ReturnType to let TypeScript infer it for you. This is great for functions that return complex objects—no need to duplicate the shape in a type definition.
Example:
function fetchUser() { return { id: 789, username: "jane_doe", preferences: { darkMode: true, notifications: false } }; } // Extract the return type of fetchUser type User = ReturnType<typeof fetchUser>; // Now you can use this User type to type variables or other functions const currentUser: User = { id: 1011, username: "john_smith", preferences: { darkMode: false, notifications: true } };
keyof) Combine typeof with keyof to create a type that only includes the keys of an existing object. This prevents invalid key access and makes your code more robust.
Example:
const productCategories = { electronics: "Electronics", clothing: "Clothing", homeGoods: "Home Goods" }; // Create a type that only includes the keys of productCategories type Category = keyof typeof productCategories; // Function that only accepts valid category keys function getCategoryLabel(category: Category): string { return productCategories[category]; } // Valid call getCategoryLabel("electronics"); // "Electronics" // Invalid call: TypeScript errors on "books" (not a valid key) getCategoryLabel("books");
At its core, typeof is all about leveraging TypeScript's inference to avoid redundant type definitions. It keeps your code DRY (Don't Repeat Yourself) and ensures consistency between your runtime values and static types.
内容的提问来源于stack exchange,提问作者Aston Richworth

