Loading lessons...
keyof & typeof Operators
keyof & typeof Operators
TypeScript provides type-level operators to inspect object shapes and infer types from existing runtime values.
The keyof Operator
The keyof operator takes an object type and produces a string or numeric literal union of its keys.
interface Person {
name: string;
age: number;
location: string;
}
type PersonKeys = keyof Person; // "name" | "age" | "location"
The typeof Operator in Type Contexts
In type annotations, typeof extracts the TypeScript type of an existing variable or object.
const defaultConfig = {
host: "localhost",
port: 8080,
debug: true
};
type AppConfig = typeof defaultConfig;
/*
Resulting type:
{
host: string;
port: number;
debug: boolean;
}
*/
Combining keyof and typeof
type ConfigKey = keyof typeof defaultConfig; // "host" | "port" | "debug"
TL;DR
keyof Treturns a union of all property key names of typeT.typeof valin a type context extracts the static type of a runtime value.keyof typeof objgets property key unions directly from JavaScript objects.