I've got two functions which do exactly the same thing so it seems like a prime candidate for a generic function to replace them. However I can't quite get it right, the extracted value isn't exactly the same as the original type as the return type should be the original result/error type but now without undefined.
type Value = string;
type PurchaseResult = {
result: Value | undefined,
error: Error | undefined,
}
One of the existing examples of the function (for the other function replace key and type with result/value:
const extractErrors = (
purchaseResults: PurchaseResult[]
) =>
purchaseResults
.map(({ error }) => error)
.filter((error): error is Error => Boolean(error));
Failed Attempt
const extractOnlyDefinedValuesFromArrayOfObjects = <
T,
K extends keyof A,
A extends { [k in K]: T }
>(
list: A[],
key: K
): T[] =>
list
.map((obj) => obj[key])
.filter((value) => typeof value !== 'undefined');
const extractedResults = extractOnlyDefinedValuesFromArrayOfObjects<
Value,
'result',
PurchaseResult
>('result', arrayOfResults);
Thanks!