The keyof operator takes an object type and produces a string or numeric literal union of its keys. Combined with indexed access lookup types (T[K]), keyof enables type-safe dynamic property access.
flowchart LR
A["interface User { id: number; name: string; email: string; }"] --> B["keyof User"]
B --> C["'id' | 'name' | 'email'"]
interface SystemConfig {
host: string;
port: number;
sslEnabled: boolean;
maxRetries: number;
}
// ConfigKey type is 'host' | 'port' | 'sslEnabled' | 'maxRetries'
type ConfigKey = keyof SystemConfig;
const config: SystemConfig = {
host: "api.kodersolution.com",
port: 443,
sslEnabled: true,
maxRetries: 3
};
// Type-safe property getter function
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const hostName: string = getProperty(config, "host");
const portNum: number = getProperty(config, "port");
// getProperty(config, "invalidKey"); // Compiler Error: Argument of type '"invalidKey"' is not assignable to parameter of type 'keyof SystemConfig'
console.log(`Server Host: ${hostName}:${portNum}`);
keyof with Generics: Use <T, K extends keyof T> for generic object property manipulation functions.keyof any Yields string | number | symbol: The top key type representing any valid property key.Type["propertyName"].Create a type UserKeys = keyof { id: number; name: string }. Verify that UserKeys evaluates to "id" | "name".
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With