Generics and Known Fields
If you want to use a generic and refer to its fields, use this.
<T, K extends keyof T>(field: K) =>
T
is your typekeyof T
- union of the keys of TK extends
- makes that list of keys a type
Now you can also specify what field
is, the K
(or key) type.
Example
const sortBy = <T, K extends keyof T>(field: K) =>
(a: T, b: T): number => {
const aValue = a[field]
const bValue = b[field]
if (aValue < bValue) {
return -1
} if (aValue < bValue) {
return 1
}
return 0
}
type Measurement = {
degrees: number,
}
const byDegrees = sortBy<Measurement, 'degrees'>('degrees')