keyof and typeof
| Keys of T | |
| Types from values | |
| Indexed access T[K] | |
| Config objects |
Keys of T
keyof collects the property names of an object type into a union of literals. It is the typesafe way to talk about keys.
UserKey is name or age, so only real fields are accepted. A typo becomes a compile error instead of undefined at runtime.
type User = {
name: string;
age: number;
};
type UserKey = keyof User; // "name" | "age"
Types from values
typeof lifts a value into the type world, capturing the shape TypeScript inferred for it. No hand-written duplicate is needed.
Settings mirrors the settings object exactly, including the number type of pageSize. Change the value and the type follows.
const settings = {
theme: "dark",
pageSize: 20,
};
type Settings = typeof settings;
Indexed access T[K]
Indexed access reads one property type out with square brackets. User of name is string, just like field access but for types.
Unions of keys work too, so name or age gives string or number. This pairs well with keyof for fully derived lookups.
type Name = User["name"]; // string
type Either = User["name" | "age"]; // string | number
Config objects
Config objects tie the three ideas together. Functions accept the derived key and value types instead of loose strings.
getUserField returns the right value type for any valid key, and getPageSize reads the settings shape. Callers get autocomplete for free.
function getUserField(user: User, key: UserKey): string | number {
return user[key];
}
function getPageSize(config: Settings): number {
return config.pageSize;
}
Next: Utility types
Article author: Arthur Isaev