英文:
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<typeof ObjC>
I want a function for decoding this object and returning an Error (not DecoderError). Similar to:
import { fold } from 'fp-ts/lib/Either'
import { pipe } from 'fp-ts/lib/function'
const decodeObj = async (str: string): Promise<Either<Error, ObjType>> => {
return pipe(
ObjC.decode(str),
fold(err => toError(err), m => m), // This doesn'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 'fp-ts/lib/Either';
// -- rest of your code --
const decodeObj = async (str: string): Promise<Either<Error, ObjType>> => {
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论