簡體   English   中英

將兩個功能合二為一

[英]Combine two functions into one

這里的目標是從 2 個帶有參數組合的函數創建一個函數。 使用 JavaScript 可以輕松完成,但使用打字稿並不容易。

結合兩個功能的一種方法是Proxy 例子:

const f1 = (a: number) => {
    return (a + 1) * 2;
} 

const f2 = (b: string, c: string[]) => {
    c.push(b);
    return c;
}

const combiner = (f1: Function, f2: Function) => {
    return new Proxy(f1, {
        apply(target, thisArg, args) {
            const f1_args = args.slice(0, f1.length);
            const f2_args = args.splice(f1.length);
            f1(...f1_args);
            f2(...f2_args);
        }
    });
};

const f = combiner(f1, f2);

f(1, 'foo', ['bar']); // Typehints?

問題是可以用打字稿輸入combiner函數的類型提示結果嗎?

通過使用兩個泛型類型A1A2來簡單地鍵入組合函數的參數,這兩個泛型類型保存兩個函數的參數元組類型。

const combiner = <
  A1 extends any[], 
  A2 extends any[]
>(f1: (...args: A1) => void, f2: (...args: A2) => void) => {
    return new Proxy(f1, {
        apply(target, thisArg, args) {
            const f1_args = args.slice(0, f1.length);
            const f2_args = args.splice(f1.length);
            f1(...f1_args as A1);
            f2(...f2_args as A2);
        }
    }) as unknown as (...args: [...A1, ...A2]) => void
};

我們只需要斷言返回的類型是一個以組合的A1A2元組作為其參數類型的函數。

const f = combiner(f1, f2);
//    ^? const f: (a: number, b: string, c: string[]) => void

f(1, 'foo', ['bar']);

操場

暫無
暫無

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

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