Currently, I am attempting to analyze the characteristics of objects within arrays. In order to maintain type safety, I am utilizing a getter function to access the child object of the array objects (if necessary) that contains the specific property to be observed.
The propertyName / key
must be a string since the observe library I am utilizing requires it.
The getter should have the capability to accept a function that returns the same type that was initially provided, such as o => o
.
Below is a concise example:
function example<A, B>(
array: A[],
getter: (ao: A) => B,
key: keyof B,
callback: (value: B[keyof B]) => void
) {
callback(getter(array[0])[key]);
}
example([{b: {c: 1}}], a => a.b, "c", v => {});
Unfortunately, this results in the error message:
Argument of type '"c"' is not assignable to parameter of type 'never'.
However, the following example does function correctly:
function alternate<A>(
array: A[],
key: keyof A,
callback: (value: A[keyof A]) => void
) {
callback(array[0][key]);
}
alternate([{b: 1}], "b", v => {});
Why is the compiler struggling to infer the type of B
and are there any potential workarounds I could implement?