TypeScript keyof and typeof Operators
The `keyof` operator produces a union of all the property names (as string literal types) of a given type. It's useful for writing functions that safely access any property of an object.
The `typeof` operator, when used in a type context, extracts the type of a variable or value, letting you reuse an inferred type without writing it out manually again.
type UserKeys = keyof User;
type ConfigType = typeof config;keyof
For `interface User { name: string; age: number }`, `keyof User` produces the type `"name" | "age"`, a union of all property name literals.
typeof in type positions
Writing `typeof someVariable` inside a type annotation captures the exact inferred type of that variable, which is handy for deriving types from existing values.
interface User {
name: string;
age: number;
}
function getProp(user: User, key: keyof User) {
return user[key];
}
const u: User = { name: "Lin", age: 27 };
console.log(getProp(u, "name"));Linkeyof User restricts key to only valid property names of User, catching typos at compile time.
const config = { host: "localhost", port: 8080 };
type Config = typeof config;
const other: Config = { host: "example.com", port: 3000 };
console.log(other);{ host: 'example.com', port: 3000 }typeof config captures the object's inferred shape as a reusable type.
Key points
- keyof produces a union of a type's property names as string literals.
- keyof is often used to safely restrict function parameters to valid keys.
- typeof, in a type position, extracts the type of an existing variable.
- Both operators help you derive new types from existing code instead of duplicating them.
