Home > Software engineering >  Unable to get type of object property
Unable to get type of object property

Time:05-30

Is that possible to get the type of object property if that object is contained in table?

const data = [{
  prop1: 123,
  prop2: "fgdgfdg",
}, {
  prop1: 6563,
  prop2: "dfhvcfgj",
}]

const getValuesOfProp = <ROW extends object>(key: keyof ROW, input: ROW[]): ROW[keyof ROW][] => {
  return input.map((item) => {
    return item[key]
  })
}

const result = getValuesOfProp('prop2', data)

The type of the result is Array<string | number> but should be Array<string>.

This is example from more complicated case: what I want to have is typed value as number in CellContent. Type should be got from 'key2' in object contained in data array.

<Table headers={[{id: 'key2', Cell: (value) => <CellContent value={value} />}]} data={[{ key1: 'dsgfg', key2: 123}, {key1: 'dsgdfg', key2: 4356}]} />

CodePudding user response:

You need to add second generic parameter for your key:

const getValuesOfProp = <ROW extends object, TKey extends keyof ROW>(key: TKey, input: ROW[]): ROW[TKey][] => {
    return input.map((item) => {
        return item[key]
    })
}

Playground

CodePudding user response:

You need to add the the key as a generic type too.

const getValuesOfProp = <ROW, K extends keyof ROW>(key: K, input: ROW[]): ROW[K][] => {
  return input.map((item) => {
    return item[key]
  })
}

If you just return ROW[keyof ROW][], TypeScript will not know that this should correlate with the passed key property.

Playground

  • Related