What Is keyof in TypeScript?
The keyof operator creates a union of the property
keys of a type. It is useful when you need to refer to object properties while preserving
TypeScript's static type checking.
Instead of accepting any string as a property name, you can use
keyof to restrict a value to keys that actually
exist on a particular type.
type User = {
id: number;
name: string;
email: string;
};
type UserKey = keyof User;
// Equivalent to:
// "id" | "name" | "email"
const key: UserKey = "name"; // Valid
// Error: "age" is not a key of User
// const invalidKey: UserKey = "age";
In this example, keyof User produces the union
"id" | "name" | "email". TypeScript checks assignments
against that union during compilation.
How Does keyof Work?
TypeScript evaluates keyof against a type's known
property keys. The result is a type, not a runtime array of property names.
type Product = {
productId: number;
title: string;
price: number;
inStock: boolean;
};
type ProductKey = keyof Product;
// "productId" | "title" | "price" | "inStock"
let productKey: ProductKey;
productKey = "price";
productKey = "inStock";
// Compile-time error:
// productKey = "description";
This makes keyof valuable for reusable APIs,
property-based utilities, sorting functions, table configurations, and generic object
operations.
Remember that keyof operates on a type's declared
keys. It does not inspect a runtime object or return its actual keys when the program runs.
How Do You Use keyof with Generic Functions?
One of the most practical uses of keyof is to constrain
a function parameter to valid keys of another parameter's type.
function getProperty(
object: T,
key: K
): T[K] {
return object[key];
}
const user = {
id: 42,
name: "Abhinash",
active: true
};
const userName = getProperty(user, "name");
// string
const userId = getProperty(user, "id");
// number
// Compile-time error:
// getProperty(user, "email");
This example combines three important TypeScript concepts:
Trepresents the object type.K extends keyof Trestricts the key to a valid property.T[K]represents the type of the selected property.
Because the return type depends on the selected key, calling the function with
"name" produces a string type, while calling it
with "id" produces a number type.
This relationship is more precise than returning a broad union of every property type.
What Does K extends keyof T Mean?
The expression K extends keyof T is a generic
constraint. It tells TypeScript that the type represented by
K must be assignable to the keys of
T.
type Settings = {
theme: string;
notifications: boolean;
};
function updateSetting(
key: K,
value: Settings[K]
): void {
console.log(key, value);
}
updateSetting("theme", "dark");
updateSetting("notifications", true);
// Errors:
// updateSetting("language", "en");
// updateSetting("theme", true);
Here, the key and value are connected. The
theme property expects a string, while
notifications expects a boolean.
This prevents many accidental mismatches when working with typed configuration objects.
In more complex generic APIs, inference can sometimes widen a generic type or infer a union of possible keys. When the key and value must be correlated very strictly, a discriminated union or tuple-based API may provide stronger guarantees.
How Does keyof Work with Interfaces?
The operator works with interfaces in the same way it works with object type aliases. It extracts the known property keys from the interface.
interface Employee {
employeeId: number;
fullName: string;
department: string;
}
type EmployeeKey = keyof Employee;
// "employeeId" | "fullName" | "department"
function logEmployeeField(
employee: Employee,
key: EmployeeKey
): void {
console.log(employee[key]);
}
This is particularly useful when multiple parts of an application share a common interface. Functions can accept valid property names without repeating a separate string union for every model.
What Happens When You Use keyof with Index Signatures?
An index signature describes a type that supports property access through a broader key
category. Because the type permits arbitrary keys of that category,
keyof can produce broader types instead of a finite
union of named properties.
type Dictionary = {
[key: string]: number;
};
type DictionaryKey = keyof Dictionary;
// string | number
const firstKey: DictionaryKey = "score";
const secondKey: DictionaryKey = 10;
For a string index signature, the result includes
string | number. JavaScript converts numeric property
keys to strings, which explains why numeric keys are included.
A numeric index signature behaves differently:
type NumberDictionary = {
[index: number]: string;
};
type NumberDictionaryKey = keyof NumberDictionary;
// number
These results matter when writing generic utilities because an index signature can make the permitted key space much broader than a small set of literal property names.
How Does keyof Work with Union Types?
When keyof is applied directly to a union type,
it gives keys that are safely available on every member of the union.
type Admin = {
id: number;
name: string;
permissions: string[];
};
type Customer = {
id: number;
name: string;
loyaltyPoints: number;
};
type Person = Admin | Customer;
type PersonKey = keyof Person;
// "id" | "name"
Both union members have id and
name, so those are the safe shared keys.
The permissions and
loyaltyPoints properties are not present on every
member and therefore are not included in this direct result.
If you need keys from any member of a union, a distributive conditional type can help:
type KeysOfUnion =
T extends unknown ? keyof T : never;
type AllPersonKeys = KeysOfUnion;
// "id" | "name" | "permissions" | "loyaltyPoints"
The conditional type distributes across union members because
T is a naked type parameter on the left side of
extends. Each member's keys are computed separately
and then combined into a union.
How Does keyof Work with typeof?
The JavaScript operator typeof can be used in a
TypeScript type position to obtain the inferred type of a value. Combining it with
keyof lets you derive keys from an existing object
without separately declaring its type.
const appConfig = {
appName: "IgKnight",
version: "1.0.0",
enableAnalytics: false
};
type AppConfig = typeof appConfig;
type AppConfigKey = keyof AppConfig;
// "appName" | "version" | "enableAnalytics"
const configKey: AppConfigKey = "version";
This pattern is useful for configuration objects, constant maps, action names, feature flags, and other values that serve as the source of truth for their own types.
By deriving types from values, you reduce duplication and lower the risk of a manually maintained type becoming inconsistent with the object.
How Can keyof Improve Type-Safe Sorting?
A sorting function can use keyof to restrict its
property argument to keys that exist on the records being sorted.
type Student = {
name: string;
score: number;
};
function sortByKey(
items: T[],
key: K
): T[] {
return [...items].sort((a, b) => {
const left = a[key];
const right = b[key];
if (left < right) return -1;
if (left > right) return 1;
return 0;
});
}
const students: Student[] = [
{ name: "Maya", score: 82 },
{ name: "Arun", score: 95 },
{ name: "Sara", score: 88 }
];
const byName = sortByKey(students, "name");
const byScore = sortByKey(students, "score");
This example demonstrates the key constraint, but it assumes the selected property values can be compared using JavaScript's relational operators. A production sorting utility may need an explicit comparator to handle dates, nullable values, locale-aware strings, or domain-specific ordering.
Common keyof Mistakes
Assuming keyof returns a runtime array
keyof produces a type-level union. Use Object.keys() when you need runtime property names, and remember its return type is string[] rather than a guaranteed exact key union.
Using an unrestricted string key
A string parameter accepts arbitrary property names. Use K extends keyof T when the function should accept only keys of a particular type.
Confusing keyof with property values
keyof produces property keys, not property value types. Use T[K] to obtain the value type associated with a selected key.
Forgetting shared keys in unions
keyof (A | B) includes keys available on both union members. Use a distributive conditional type if you need to collect keys from every member.
Best Practices for Using keyof
- Use
keyofto make object-property APIs type-safe. - Combine
K extends keyof TwithT[K]when the value type depends on the selected key. - Use
typeofwhen deriving keys from an existing value. - Understand index signatures before assuming the result is a finite union of string literals.
- Use runtime validation when property names come from external input; static types do not validate incoming data.
- Keep generic helpers focused so their constraints express the actual guarantees the function needs.
Final Takeaway
The keyof operator extracts the known keys of a
TypeScript type and represents them as a union. It becomes especially powerful when
combined with generics, typeof, and indexed access
types such as T[K].
Use it to build type-safe property accessors, configuration utilities, sorting helpers, and reusable APIs. Keep in mind that it is a compile-time feature: it does not inspect objects at runtime or replace runtime validation for untrusted data.