#arg: keyof T and T[arg] is a number

19 messages · Page 1 of 1 (latest)

night hare
#

I have a class that takes a generic T. I want to guarantee that the argument objectKey is a key of the object that conforms to T, and that T[objectKey] is a number.

class MyClass<T> {
  constructor(public objectKey: keyof T) {}
}
unkempt wave
#

perhaps something like this?
class MyClass<K extends PropertyKey, T extends Record<K, number>>
then use K

#

weird pattern though, why do you need something like this

night hare
#

It's a priority queue-like class that automatically sorts items on a given property key. I'm just trying to make that key able to be checked at compile time.

unkempt wave
#

why enforce that it's a number then? i feel you could also do sorting by Date or string or whatever

night hare
#

Is there a way I could avoid having to pass in an additional type argument? Currently, this solution seems to break existing usage of the class.

unkempt wave
night hare
night hare
unkempt wave
night hare
night hare
unkempt wave
#

do those node classes have other properties that you're sorting by?

night hare
#

yeah, the naming varies

#

I guess I could have an union somwhere of all the different keys, but that just feels like way overcompilcating

unkempt wave
#

i feel sort-like callbacks are the way to go there

unkempt wave
night hare