I am developing a function that takes in an array of objects and resamples the array based on a property of the objects. (More theory on that in my question resampling an array of objects. In typescript, the function starts like this:
export function resample<T>(
originalArray: Array<T>,
sortKey: keyof T,
samplingInterval: number
): Array<T> {
const array = [...originalArray];
let queuedItem = array.shift();
let t0: number = queuedItem[sortKey]; // <-------- problem here
// ... more code
}
When trying to type t0 as a number, I get the error:
Type 'T[string]' is not assignable to type 'number'
TypeScript playground demonstrating the issue
Without explicitly defining the type, t0 is typed as T[keyof T]. Which makes sense. But later in the code, I do some simple math with t0, and I need it ot be treated as a number.
Why can T[string] not be assignable to a number type? We have no information thus far about what's in T, why does typescript prohibit that T[keyof T] from being a number?
Can I better type this function, and T? It must be that T has at least one property whose value is a number, but whose key could be any string, and when being used in the resample function, sortKey is any property of T whose value is a number?
queuedItem[sortKey], so it can be NOT a number.