Let's say I want to write a sortBy
function, that takes a list of T
s and a key of T to sort the list by.
To properly work I want the key to only accept keys of T that are numeric.
I have this, but I don't know how to restrict Key
so that T[Key]
refers to a number:
const sortBy = <T, Key extends keyof T>(items: T[], key: Key) {
// impl
}
I played around with this, but could not get it to work:
type NumericAttributesOf<T> = {
[K in keyof T]: T[K] extends number ? T[K] : never
}
Update:
based on the answer to this question this is what I ended up with:
type KeysMatching<T, V> = {
[K in keyof T]: T[K] extends V ? K : never
}[keyof T]
function sortBy<T>(items: T[], key: KeysMatching<T, number>): T[]
function sortBy<K extends PropertyKey>(
items: Record<K, number>[],
key: K,
): Record<K, number>[] {
return [...items].sort((a, b) => a[key] - b[key])
}