簡體   English   中英

打字稿功能類型推論

[英]Typescript Functional Type Inference

我編寫了這個簡單的compose函數,效果很好。 但是,為了確保類型安全,我不得不訴諸使用泛型為編譯器提供類型提示,即使很容易推斷出“ upperCaseAndLog”的簽名也是如此。

 const compose = <T, R>(...fns: Array<(a: any) => any>) => (a: T): R => fns.reduce((b, f) => f(b), a); const greet = (s: string) => "Hello " + s; const toUpperCase = (s: string) => s.toUpperCase(); const log = console.log; const upperCaseAndLog = compose<string, void>( greet, toUpperCase, log ); upperCaseAndLog("bill"); 

我是否缺少某些東西,是否有更優雅的方法來實現相同的目標? 我假設像F#或Haskell這樣的語言將能夠推斷類型而無需任何其他信息。

Typescript無法推斷此類鏈接類型(在某種意義上,鏈接是指該函數的參數取決於前一個函數的結果)。

您甚至無法以足夠通用的方式定義compose的簽名,以使其可以用於多種功能。 我們可以做的是定義可以接受給定數量的功能的重載:

type Fn<A, R> = (a: A) => R // just to be a bit shorter in the compose signature, you can use teh function signature directly  
function compose<T, P1, P2, R>(fn1: Fn<T, P1>, fn2: Fn<P1, P2>, f3: Fn<P2, R>) : Fn<T, R>
function compose<T, P1, R>(fn1: Fn<T, P1>, f2: Fn<P1, R>) : Fn<T, R>
function compose(...fns: Array<(a: any) => any>) {
    return function (a: any) {
        return fns.reduce((b, f) => f(b), a);
    }
}

const greet = (s: string) => "Hello " + s;
const toUpperCase = (s: string) => s.toUpperCase();
const log = console.log;

const upperCaseAndLog = compose(
    greet,
    toUpperCase,
    log
);

upperCaseAndLog("bill");//(a: string) => void

暫無
暫無

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

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