我正在尝试使用 TypeScript 并尝试使用fp-ts
类型对域逻辑进行建模,但我遇到了这个问题:
import { left, right, Either } from "fp-ts/lib/Either";
type MyType = {
id: string,
isValid: boolean,
}
type MyValidType = {
id: string,
isValid: true,
}
type CreateMyValidType = (t: MyType) => Either<Error, MyValidType>
// Compile error!
const createMyValidType: CreateMyValidType = t => {
switch (t.isValid) {
case true:
return right({
id: "test",
isValid: true
})
default:
return left(new Error())
}
}
编译器对我大喊大叫,因为:
Type '(t: MyType) => Either<Error, { id: string; isValid: boolean; }>' is not assignable to type 'Either<Error, CreateMyValidType>'.
如果我删除Either
并且我只返回 sum 类型Error | MyValidType
就可以了。
type CreateMyValidType = (t: MyType) => Error | MyValidType
// This compiles
const createMyValidType: CreateMyValidType = t => {
switch (t.isValid) {
case true:
return {
id: "test",
isValid: true
}
default:
return new Error()
}
}
它在里面时似乎无法识别正确的类型Either
!
我找到了通过指定right
调用时的类型来避免问题的方法,但我不完全理解其中的含义,所以我不知道这是否是一个坏主意:
return right<Error, MyType2>({
id: "test",
isValid: true,
});
处理此问题并使其编译的正确方法是什么?谢谢!