type CheckFunction<T> = (value: T) => boolean;
type ResultFunction<T> = (arr: T[]) => T | undefined;
type FindFunction = <T>(checkCallback: CheckFunction<T>) => ResultFunction<T>;
const findElement: FindFunction = (checkCallback) => {
return (array) => {
for (let index = 0; index < array.length; index++) {
if (checkCallback(array[index])) {
return array[index];
}
}
return undefined;
};
};
const myNumbersArray = [1, 5, 4, 9];
const resultOne = findElement<number>((val) => val > 1)(myNumbersArray); // it works but explicitly defines the type 'number' in findElement<number>
const resultTwo = findElement((value: number) => value > 1)(myNumbersArray); // it works but explicitly defines the type 'number' in the check callback (value: number)
const resultThree = findElement((val) => val > 1)(myNumbersArray); // calling findElement() the way I want to, but both 'val' and 'resultThree' are 'unknown'
// ^
// Object is of type 'unknown'.
I'm deepening my understanding of Typescript and functional programming and encountered this issue:
I've created a higher order findElement
function that should locate the first element in an array that meets a specific condition.
Here's my question:
Is there a way to enhance my typings so that the generic type T
used in CheckFunction can be deduced from the type of elements in myNumbersArray
without explicitly setting it as number
? Additionally, the returned value from findElement()()
should have the same type as the array elements or undefined
if no element matches.
Access the TS Playground.