Learn how to query object property keys using keyof and extract types from runtime JavaScript variables using typeof.
Discover how TypeScript infers types automatically and how let versus const declarations shape wide types versus narrow literal types.
TypeScript provides two key operators to bridge the gap between runtime JavaScript values and compile-time types: typeof and keyof.
typeof Operator (in Type Space)In type space, typeof queries the static TypeScript type of a runtime JavaScript variable or object:
const appConfig = {
apiEndpoint: "https://api.devloom.dev",
timeout: 5000,
maxRetries: 3,
};
// Extract type shape directly from the runtime variable!
type AppConfig = typeof appConfig;
/*
Inferred as:
type AppConfig = {
apiEndpoint: string;
timeout: number;
maxRetries: number;
};
*/
keyof OperatorThe keyof operator takes an object type and produces a string or numeric union of its property keys:
type User = {
id: number;
name: string;
email: string;
};
type UserKeys = keyof User; // Inferred as: "id" | "name" | "email"
const key: UserKeys = "name"; // Valid!
// const badKey: UserKeys = "age"; // Error: Type '"age"' is not assignable
keyof typeofExtract property keys directly from a runtime JavaScript object:
const COLORS = {
primary: "#3178C6",
secondary: "#F7DF1E",
accent: "#FF4081",
} as const;
type ColorKey = keyof typeof COLORS; // "primary" | "secondary" | "accent"
typeof x === "string" evaluates a string at runtime. Type-space type T = typeof x queries static compile-time type shapes!Use keyof typeof for type-safe dictionary lookups. Next, let's explore Conditional Types and the infer keyword!