Code Logo

Object Keys with keyof

Published at25 Jul 2026
TypeScript Generics & Advanced Types Medium 0 views
Like0

Write a TypeScript function that takes an object and a key, and returns the value at that key. Use the generics to ensure the key parameter is always a valid property name of the object. The keyof operator produces a union of all property names of a type.

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

Example 1
Input
{"x":10,"y":20},"x"
Output
10
Explanation

Access coordinate

Example 2
Input
{"name":"Bob","age":25},"age"
Output
25
Explanation

Access number property

Example 3
Input
{"active":true},"active"
Output
true
Explanation

Boolean property

Example 4
Input
{"name":"Alice","age":30},"name"
Output
Alice
Explanation

Access string property

Example 5
Input
{"title":"Test"},"title"
Output
Test
Explanation

Single property

Algorithm Flow

Recommendation Algorithm Flow for Object Keys with keyof
Recommendation Algorithm Flow for Object Keys with keyof

Solution Approach

function solution<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

Best Answers

typescript - Approach 1
function solution<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}