Object Keys with keyof
Write a TypeScript function that takes an object and a key, and returns the value at that key. Use the generics
The keyof operator is a TypeScript-specific type operator that yields a union type of all keys of a given type. For an interface Person { name: string; age: number }, keyof Person evaluates to "name" | "age". Combined with K extends keyof T, this constrains the key parameter to only valid keys of the object type.
This pattern is fundamental to TypeScript's type system. It enables type-safe property access without casting or any. The return type T[K] (indexed access type) ensures the returned value has the correct type for the property. The compiler catches invalid key access at compile time.
Time complexity is O(1) as property access is constant time. Space complexity is O(1). The type-level computation has zero runtime cost as TypeScript types are erased during compilation.
Edge cases include objects with optional properties (keyof includes optional keys), arrays (keyof includes number and method names), and empty objects (keyof produces never).
Example Input & Output
Access coordinate
Access number property
Boolean property
Access string property
Single property
Algorithm Flow
Solution Approach
Use the keyof operator to create a type representing all keys of another type. keyof T produces a union of the property names of type T. This allows type-safe access to object properties.
keyof is often combined with generics for type-safe property access and manipulation. It enables patterns like Pick<T, K> and Omit<T, K>.
Time O(1), Space O(1).
Best Answers
function solution<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
