Careeroza
The typeof Type Operator
Types From Values
In a type position, typeof value gives the TypeScript type of a variable (not the runtime string from JavaScript typeof). It lets you write the value first and derive the type from it.
Example
const defaultConfig = {
apiUrl: "https://api.shopease.in",
timeoutMs: 5000,
retries: 3,
features: { wishlist: true, reviews: false },
};
type Config = typeof defaultConfig;
function withOverrides(overrides: Partial<Config>): Config {
return { ...defaultConfig, ...overrides };
}
const cfg = withOverrides({ timeoutMs: 8000 });
console.log(cfg.timeoutMs, cfg.features.wishlist);
console.log(typeof cfg.retries); // this is the JavaScript typeofOutput
8000 true number
typeof with as const
Example
Combined with as const and keyof, you can derive a union from an object of constants.
const ROLES = { ADMIN: "admin", SELLER: "seller", BUYER: "buyer" } as const;
type RoleKey = keyof typeof ROLES; // "ADMIN" | "SELLER" | "BUYER"
type Role = (typeof ROLES)[RoleKey]; // "admin" | "seller" | "buyer"
function homePage(role: Role): string {
return role === "admin" ? "/admin" : role === "seller" ? "/seller/dashboard" : "/";
}
const keys = Object.keys(ROLES) as RoleKey[];
keys.forEach((k) => console.log(k.padEnd(6), homePage(ROLES[k])));Output
ADMIN /admin SELLER /seller/dashboard BUYER /