As I develop a method to iterate over an array of objects, my goal is to incorporate the use of an iteratee
in a similar manner as lodash. The iteratee
should be able to act as either a key within the object or a function that accepts the object and returns a value. Furthermore, I aim to enforce constraints on the type of the resulting value.
Initially, I require the functionality to retrieve all keys of a specific type that match a particular value type.
type KeysMatchingValueType<T, V> = {
[K in keyof T]-?: T[K] extends V ? K : never;
}[keyof T];
Subsequently, I define the Iteratee
type.
type Iteratee<T, V> = KeysMatchingValueType<T, V> | ((item: T) => V);
Lastly, there exists a function that takes an object of type T
along with an Iteratee
, returning a value.
function getNumericValueFromIteratee<T>(
item: T,
iteratee: Iteratee<T, number>
): number {
return typeof iteratee === 'function' ? iteratee(item) : item[iteratee];
}
Nevertheless, TypeScript generates an error:
Type 'number | T[KeysMatchingValueType<T, number>]' is not assignable to type 'number'.
Type 'T[KeysMatchingValueType<T, number>]' is not assignable to type 'number'.
Type 'T[T[keyof T] extends number ? keyof T : never]' is not assignable to type 'number'.
Type 'T[keyof T]' is not assignable to type 'number'.
Type 'T[string] | T[number] | T[symbol]' is not assignable to type 'number'.
Type 'T[string]' is not assignable to type 'number'.