#How to value, type T[keyof T] not assignable to string for value?

12 messages · Page 1 of 1 (latest)

clever plume
#
  t: dbThunkFunction,
  table: string,
  columns: Array<keyof T>,
  data: T[]
) {

  const values: string[] = [];
  data.forEach((entry: T) => {
    columns.forEach((colName: keyof T) => {
      const value = entry[colName];
      values.push(value); //how to type value?
    });
  });```
#

How to value, type T[keyof T] not assignable to string for value?

simple root
#

values is a string[]
so value must be a string
so entry[colName] must be a string too
so entry must be a Record<unknown, string>

#

which it probably isn't

#

hence the error

clever plume
#

how can i type entry then if I typed data as a generic type, im trying to avoid value: any. The suggestion Record<unknown, string> didnt work

simple root
#

how about

sour mortarBOT
#
Ascor8522#7606

Preview:```ts
declare type dbThunkFunction = unknown

export async function update<T>(
t: dbThunkFunction,
table: string,
columns: Array<keyof T>,
data: T[]
) {
const values = data
.map(entry =>
columns.map(colName => entry[colName])
)
.flat()
}```

simple root
#

looping over an array an mutating another array really isn't a great way to do what you're trying to do

#

try always creating a new array instead of mutating an existing one

#

it's way cleaner and way easier to type

#

@clever plume