如何在io-ts中正确地定义一个函数

huangapple go评论50阅读模式
英文:

How to correctly type a function in io-ts

问题

const decodeObj = async (str: string): Promise<Either<Error, ObjType>> => {
  return pipe(
    ObjC.decode(str),
    fold(
      err => new Error(err.message), // Ensure an Error is returned
      m => right(m), // Use `right` to wrap the successful result
    ),
  )
}
英文:

I have the following:

export const ObjC = Codec.struct({
  name: Codec.string,
  value: Codec.number,
})

export type ObjType = Codec.TypeOf&lt;typeof ObjC&gt;

I want a function for decoding this object and returning an Error (not DecoderError). Similar to:

import { fold } from &#39;fp-ts/lib/Either&#39;
import { pipe } from &#39;fp-ts/lib/function&#39;

const decodeObj = async (str: string): Promise&lt;Either&lt;Error, ObjType&gt;&gt; =&gt; {
  return pipe(
    ObjC.decode(str),
    fold(err =&gt; toError(err), m =&gt; m), // This doesn&#39;t do want I want
  )
}

How can I return the right types for this function in an idiomatic way?

答案1

得分: 1

根据你列出的返回类型,听起来你想在值为Left时对左侧的值执行转换,而当值为Right时保持代码不变。在这种情况下,mapLeft 辅助函数正是你要找的。

可以通过以下方式实现:

import { mapLeft } from 'fp-ts/lib/Either';
// -- 你的其余代码 --

const decodeObj = async (str: string): Promise<Either<Error, ObjType>> => {
  return pipe(
    objCodec.decode(str),
    mapLeft(toError),
  );
};

然而,我有一些问题。首先,按照现在的代码,永远无法成功解析,因为输入字符串永远不会匹配一个对象。我猜想你可能省略了其他逻辑部分,但目前这段代码看起来有点不正确。

英文:

Just going off of the return type you've listed, it sounds to me like you want to perform a transformation to the left value when the thing is Left and leave the code unchanged when the value is Right. In that case the mapLeft helper function is exactly what you're looking for.

This can be achieved by saying:

import { mapLeft } from &#39;fp-ts/lib/Either&#39;;
// -- rest of your code --

const decodeObj = async (str: string): Promise&lt;Either&lt;Error, ObjType&gt;&gt; =&gt; {
  return pipe(
    objCodec.decode(str),
    mapLeft(toError),
  );
};

However, I have some questions. For one the code as written will never succeed to parse because the input string will never match an object. I'm guessing there are other piece of logic you've omitted, but as it stands the code looks a bit wrong.

huangapple
  • 本文由 发表于 2023年2月16日 05:02:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75465406.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定