Course contentsShow
← TypeScript
Lesson 1623 of 1,79637. Migrating JavaScript to TypeScriptFree lesson

Dynamic Property Access Patterns

Migrating code that uses bracket notation and dynamic keys without proper type safety.

Dynamic Property Access Patterns

You'll learn: How to add type safety to legacy JavaScript code that uses bracket notation and dynamic keys without losing flexibility.

The Problem with Dynamic Access

JavaScript code often uses bracket notation to access object properties dynamically:

function getValue(obj, key) {
  return obj[key];
}

const user = { name: "Alice", age: 30 };
const name = getValue(user, "name"); // "Alice"
const oops = getValue(user, "typo"); // undefined - no warning!

When migrating this pattern to TypeScript, you lose type safety completely if you leave it as-is. The compiler can't help you catch typos or track what types are returned.

Making It Type-Safe

The key is constraining the key parameter to only accept actual keys of the object using keyof:

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

const user = { name: "Alice", age: 30 };
const name = getValue(user, "name"); // string
const age = getValue(user, "age");   // number
// const oops = getValue(user, "typo"); // Error: Argument not assignable

This pattern preserves dynamic access while ensuring:

  • Only valid keys are accepted
  • Return types match the property type
  • Typos are caught at compile time

Common Migration Patterns

When you encounter obj[dynamicKey] in legacy code:

Pattern 1: Known string literal

const key = "name";
const value = obj[key]; // Works if key's type is literal "name"

Pattern 2: Runtime string

const key: string = getUserInput();
// const value = obj[key]; // Error: string not assignable to keyof T

// Solution: validate first
if (key in obj) {
  const value = obj[key as keyof typeof obj];
}

Pattern 3: Accept type looseness for truly dynamic cases

const value: unknown = obj[key as keyof typeof obj];
// Then narrow with type guards

Key Takeaway: Migrating dynamic property access means choosing between adding generic constraints for type safety (keyof T) or accepting controlled unsafety with unknown and runtime checks—avoid leaving it completely untyped.