-1

Find my current (non-working) code in the following playground please

Currently Object.fromEntries returns {[k: string]: number} dynamically, but I'd like it to be typed. It would have to return a type with exactly the keys returned by TransformedProperties method and number type for the value.

This way, when I call the transform method, it knows that the type is for example:

{
  time_worked: 10,
  other_property_one: 1,
  other_property_two: 0,
}
isherwood
  • 58,414
  • 16
  • 114
  • 157
Jedupont
  • 401
  • 1
  • 4
  • 12

1 Answers1

0

Your just going to have to cast here, Object.entries is dynamic in nature, but if your sure that these props will exist, that shouldn't be a problem.

First though, I would change your TableEntry into a type, it's practically the same as an interface, but you will get less issues using a type.

type TableEntry = {
    time_worked: number,
    other_property_one: number,
    other_property_two: number
}

Then you can cast the return into TableEntry

const transform = (rows: Row[]) => {
  return Object.fromEntries(rows.map(r => 
    [toTransformedPropertyName(r.value), r.total])) as TableEntry
} 

Updated TS Playground

Keith
  • 22,005
  • 2
  • 27
  • 44
  • Thank you for your response, I'll try. What is the advantage to use a type here over an interface please? I use interface a lot in my app actually. – Jedupont Jul 14 '23 at 14:18
  • @Jedupont You could check this out -> https://stackoverflow.com/questions/37233735/interfaces-vs-types-in-typescript Don't worry you don't need to convert all your interfaces to types, you can replace as required. If you try the playground I updated, and put back to interface you will see the issue it causes here. – Keith Jul 14 '23 at 14:22