簡體   English   中英

將聯合類型轉換為 fp-ts 中的任一類型

[英]Transforming union type into Either type in fp-ts

在打字稿中,如何將聯合類型A|B轉換為fp-tsEither<A,B> 這感覺很自然,必須有一種很好的方法來做到這一點。

我發現這是不可能的。

我最初的想法是,由於unionEither類型都是 sum 類型,因此它們在代數上是相等的。 因此,必須有一種自然而美好的方式來相互轉化。

問題是,在某一時刻,您必須對具有泛型類型的實例進行類型檢查,但根本無法在 Typescript 上執行此操作。

假設您有一個類型number | string number | string您可以執行以下操作:

import * as E from 'fp-ts/lib/Either'
import * as F from 'fp-ts/lib/function'

const toEither = F.flow(
    E.fromPredicate(
        x => typeof x === 'string', // Assuming that string is the Right part
        F.identity
    ),
)

這將產生:

toEither(4) 
{ _tag: 'Left', left: 4 }
toEither('Foo')
{ _tag: 'Right', right: 'Foo' }

但是請記住, Either不用於拆分聯合類型,而是將錯誤路徑和結果的快樂路徑包裝在一種類型中。

我只通過 ts-node 檢查了上面的代碼。 我還沒有看到 TS 為toEither函數生成的實際類型

暫無
暫無

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

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