Skip to content
Pluck a typed property from objects

    ↑↓ move · ⏎ open · esc close

    Patterns

    How do I select one property from every object and have the returned array keep that property’s type?

    Bind the key to `keyof T` and use indexed access for the return element.

    The recipe

    function pluck<T, K extends keyof T>(
      items: readonly T[],
      key: K,
    ): T[K][] {
      return items.map(item => item[key])
    }
    
    const people = [
      { id: 1, name: 'Ada' },
      { id: 2, name: 'Lin' },
    ]
    
    const names = pluck(people, 'name')
    const ids = pluck(people, 'id')

    The build compiles this and checks each result below.

    How it works

    1. 01
      K extends keyof T

      The selected property must exist on every element described by `T`.

    2. 02
      T[K][]

      The selected key determines the element type of the returned array.

    What you get

    Where it goes wrong

    For a union of differently shaped objects, `keyof T` contains only keys safe on every member. Narrow the union first or model a discriminated operation when branch-specific keys are needed.

    Takeaway

    Correlate a key parameter with `T[K]` whenever a property choice determines a result type.

    See also

    Patterns