簡體   English   中英

Typescript:如何從返回的function的入參推斷出高階泛型function

[英]Typescript: How to infer a generic type in a higher order function from the input parameter of the returned function

type FindCallback<T> = (value: T) => boolean;

type FindResult<T> = (arr: T[]) => T | undefined;

type FindFn = <T>(callback: FindCallback<T>) => FindResult<T>;

const find: FindFn = (callback) => {
    return (arr) => {
        for (let idx = 0; idx < arr.length; idx++) {
            if (callback(arr[idx])) {
                return arr[idx];
            }
        }
        return undefined;
    };
};

const myArray = [1, 5, 4, 9];
const result0 = find<number>((value) => value > 1)(myArray); // works, but explicitly defined the type 'number' in find<number>
const result1 = find((value: number) => value > 1)(myArray); // works, but explicitly defined the type 'number' in the callback (value: number)
const result2 = find((value) => value > 1)(myArray);         // my desired way of calling find(), but the callback parameter 'value' and 'result2' are both 'unknown'
//                              ^
//                      Object is of type 'unknown'.

我試圖提高我對 Typescript 和函數式編程的理解,並偶然發現了以下場景:

我有這個高階find function,它應該在滿足特定條件的數組中找到第一個元素。

我現在的問題如下:

是否可以改進我的類型,以便可以從myArray中的值類型推斷出我在 FindCallback 中使用的通用類型T ,而無需將其明確定義為number 此外, find()()的返回值應該與數組中的元素具有相同的類型,或者如果沒有找到元素則為undefined

這是TS Playground的鏈接。

如果這是一個帶有兩個 arguments: callbackarray的 function 那么它會很簡單。 實際上,您有兩個獨立的功能。 您無法根據傳遞給第二個 function 的 arguments 推斷出第一個 function 的類型。

這個高階 function 結構意味着返回的FindResult function 不需要立即調用。 const mapper = find((value) => true)的類型是什么? 這是一個 function 被調用的array ......? 如果不注釋value ,您根本無法知道最終將使用哪種類型的數組進行調用。

只有當數組是 function 的參數時,才可以基於數組類型進行推斷。

type FindFn = <T>(callback: FindCallback<T>, arr: T[]) => T | undefined;

const find: FindFn = (callback, arr) => { ...

游樂場鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM