Sub topic 2
Getting an object type's keys with keyof
This chapter covers the keyof operator: what it produces, what it counts as a key, and where it goes wrong. It assumes you know TypeScript interfaces, type aliases, and union types, and that you have seen generic type parameters. The previous chapter separated type positions from value positions. keyof works only in type positions.
What keyof does
keyof takes an object type and returns a union of its property names. Each name is a string literal type.
interface User {
id: number;
name: string;
email?: string;
}
type UserKey = keyof User; // "id" | "name" | "email"UserKey is not string. It is exactly the three names "id", "name", and "email". A variable of this type accepts those three strings and rejects everything else.
const key1: UserKey = "name"; // OK
// const key2: UserKey = "age"; // Error: Type '"age"' is not assignable to type 'keyof User'Why derive the union instead of writing it
You could write type UserKey = "id" | "name" | "email" by hand. That copy goes stale as soon as someone adds a property to User. A derived union follows the interface automatically.
A common use is a lookup table that must cover every property. Record<keyof User, string> requires one entry per key, so the compiler tells you when a new property has no entry.
interface User {
id: number;
name: string;
email?: string;
}
const labels: Record<keyof User, string> = {
id: "ID",
name: "Name",
email: "E-mail",
};
function describeField(key: keyof User): string {
return `${key} is shown as "${labels[key]}"`;
}
console.log(describeField("email")); // email is shown as "E-mail"If you add age: number to User, the labels declaration fails with a missing-property error until you add an age entry. No runtime code is involved. The check happens at compile time.
keyof works on types, not values
keyof is a type operator. Its operand must be a type. If you hand it a variable, TypeScript reports that the name refers to a value.
const user = { id: 1, name: "Ada" };
// type Keys = keyof user; // Error: 'user' refers to a value, but is being used as a type here.To get the keys of a variable, first turn the variable into a type with typeof, then apply keyof. The next two chapters cover that in detail: typeof on its own, then keyof typeof.
What counts as a key
keyof returns the names of all public members of the type. Some details are easy to get wrong.
Optional and readonly properties
Optional properties (?) and readonly properties are keys like any others. In the User example, email appears in keyof User even though it may be missing from a value. The ? affects the type of the property, not the key list.
Methods
Methods are properties, so they are keys.
interface Counter {
count: number;
increment(): void;
}
type CounterKey = keyof Counter; // "count" | "increment"Class members
For a class, keyof applied to the instance type lists only public members. Private and protected members are excluded.
class Account {
public owner = "Ada";
protected balance = 0;
private pin = 1234;
deposit(amount: number): void {
this.balance += amount;
}
check(attempt: number): boolean {
return attempt === this.pin;
}
}
type AccountKey = keyof Account; // "owner" | "deposit" | "check"Here Account means the instance type. The class constructor is a value, and keyof on its type is a different question.
Number and symbol keys
Property names in JavaScript can be strings, numbers, or symbols. keyof reflects all three.
const id = Symbol("id");
type Mixed = {
0: string;
"first-name": string;
[id]: number;
plain: boolean;
};
type MixedKey = keyof Mixed; // 0 | "first-name" | typeof id | "plain"The numeric key stays a number literal type (0), not the string "0". The symbol key appears as typeof id, the unique symbol type of that constant.
This matters because keyof T is always some subset of string | number | symbol. You cannot assume a key is a string. If you build a template literal such as ` get_${key} from a generic keyof T, TypeScript rejects it, because a symbol cannot be interpolated into a string. The usual fix is to narrow with Extract<keyof T, string>`.
keyof in generic types
Because keyof is a type operator, it works on type parameters. The result is a deferred union that TypeScript resolves when the generic is instantiated.
type KeysOf<T> = keyof T;
type PointKeys = KeysOf<{ x: number; y: number }>; // "x" | "y"This is the basis of most uses of keyof in real code. Inside a generic function, keyof T says "some key that T actually has". Later chapters build on this with K extends keyof T.
Special cases
A few operands produce results you should recognize.
type K1 = keyof {}; // never
type K2 = keyof unknown; // never
type K3 = keyof any; // string | number | symbol- An object type with no properties has no keys, so
keyof {}isnever. unknownhas no known properties, so its keys arenever.anycould have any key, so its keys are every valid key type.
The behavior with index signatures, unions, and intersections is also a special case. It is the subject of a later chapter in this tutorial.
A common mistake: Object.keys returns string[]
Developers often expect Object.keys(user) to return (keyof User)[]. It returns string[], so indexing the object with the result fails under strict.
interface User {
id: number;
name: string;
email?: string;
}
const user: User = { id: 1, name: "Ada" };
const keys = Object.keys(user); // string[]
// for (const key of keys) {
// console.log(user[key]); // Error: Element implicitly has an 'any' type
// // because expression of type 'string' can't be used to index type 'User'.
// }
const typedKeys = Object.keys(user) as (keyof User)[];
for (const key of typedKeys) {
console.log(key, user[key]);
}TypeScript uses string[] on purpose. Types are structural, so a value typed User may carry extra properties at runtime, for example { id: 1, name: "Ada", role: "admin" }. The array of runtime keys can therefore contain names that are not in keyof User.
The as (keyof User)[] cast is a promise from you to the compiler. It is safe when you know the object has no extra properties, for instance an object literal you just created. It is unsafe for data from outside, such as parsed JSON.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `'user' refers to a value, but is being used as a type here` | `keyof` applied to a variable | Use `keyof typeof user` |
| `Element implicitly has an 'any' type because expression of type 'string' can't be used to index type` | The index is `string`, not a key type | Type the index as `keyof T`, or cast the result of `Object.keys` |
| Optional property seems missing from the union | Misreading: optional keys are included | Check the type again. Use `Required<T>` only if you need the property types without `undefined` |
| `Type 'symbol' is not assignable to type 'string'` when using a generic key in a template string | `keyof T` can include numbers and symbols | Use `Extract<keyof T, string>` |
| A private field is not accepted as a key | `keyof` lists public members only | Expose a public member, or restructure the type |
Choosing between keyof and a hand-written union
Use keyof when the set of valid names is defined by an existing type. That includes form fields, table columns, and lookup tables that must stay in step with a model. Write the union by hand when the names are a separate concept that happens to overlap, for example the subset of columns that can be sorted. In that case, derive the subset from the full set so a typo is caught:
interface User {
id: number;
name: string;
email?: string;
}
type SortableKey = Extract<keyof User, "id" | "name">; // "id" | "name"Extract keeps only the members of the first union that appear in the second. If someone renames name in User, this alias shrinks to "id" instead of silently keeping a name that no longer exists. Reading Extract is enough for now. A later chapter uses the same union tools in more detail.
Summary of behavior
keyof Treturns a union of the keys ofTas literal types.- It works on types only. For a variable, use
keyof typeof variable. - Optional, readonly, and method members are included. Private and protected class members are not.
- Keys can be strings, numbers, or symbols.
keyof {}andkeyof unknownarenever.keyof anyisstring | number | symbol.Object.keysreturnsstring[]because objects may have extra properties at runtime.
Exercise
Given interface Product { sku: string; price: number; discount?: number; }, what is keyof Product, and what does const labels: Record<keyof Product, string> = { sku: "SKU", price: "Price" }; do at compile time?
Show answer
keyof Product is "sku" | "price" | "discount". The optional property discount is included. The labels declaration fails to compile because Record<keyof Product, string> requires an entry for every key, and discount is missing.
Exercise
This code fails to compile. Explain why, and give two different fixes. const settings = { theme: "dark", fontSize: 14 }; type SettingName = keyof settings;
Show answer
settings is a variable, which lives in value space, and keyof needs a type. The first fix is type SettingName = keyof typeof settings;, which gives "theme" | "fontSize". The second fix is to declare an interface such as interface Settings { theme: string; fontSize: number }, annotate the variable with it, and write type SettingName = keyof Settings;.
Exercise
A class declares public a = 1; protected b = 2; private c = 3;. What is keyof of its instance type, and why can't you use "b" as a value of that type?
Show answer
It is "a". keyof lists only public members, so the protected b and private c are excluded. "b" is therefore not assignable to the resulting type.