I want to make a function like
function sortByKey<T>(items: T[], key: string): T[] {
return items.sort((a, b) => a[key] - b[key]);
}
I need T[key] to be a number, but I'm not sure how to express that.
If I knew the key ahead of time I could obviously just do {key: number} but that doesn't work here.
I tried something like sortByKey<K>(items: {[k: K]: number}[], key: K) but that gives the error "An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead." I looked into mapped types but they don't seem to do what I need. Is something like this possible in TypeScript?
T extends { [x: string] : number }not work for you? Generics can be a part of index signature only if the signature is a template literal, and even that is a very recent addition to the languageTis like{i: number, name: string}?