Home > front end >  Unable to get type of object property contained in table
Unable to get type of object property contained in table

Time:05-31

Is that possible to get the type of object property if that object is contained in table? Please look at the playground.

function table<ROW extends object, K extends Extract<keyof ROW, string>>({
  columns,
  data,
}: {
  columns: Array<{
    id: K
    Cell: (value: ROW[K]) => any
  }>
  data: Array<ROW>
}) {
  return null
}

table({
  columns: [
    {
      id: "prop1",
      Cell: (value) => value
    },
    {
      id: "prop2",
      Cell: (value) => value
    }
  ],
   data: [
     {
       prop1: "dsfdgsfg",
       prop2: 23434245
     },

     {
       prop1: "jghfjjk",
       prop2: 346466
     }
   ]
})

What I want to have is typed value (string for prop1 or number for prop2 instead of string | number for both keys) in columns Cell component.

CodePudding user response:

You can give the argument in Cell the correct type like this:

function table<
  R extends any[]
>({
  columns,
  data,
}: {
  columns: { 
    [K in keyof R & `${bigint}`]: {
      [K2 in keyof R[K]]: { 
        id: R[K][K2], Cell: (arg: R[K][K2]) => any }
      }[keyof R[K]]
    }[keyof R & `${bigint}`][],
  data: [...R]
}) {
  return null
}

For the column property I created a union of all possible prop names with the corresponding Cell function type.

Playground

  • Related