【发布时间】:2019-10-17 15:31:07
【问题描述】:
我正在使用 fp-ts,并且我有一个返回 HttpError 对象或字符串的函数:
async getPreferencesForUserId(userId: string): Promise<Either<HttpResponseNotFound, string>> {
const preferences = await getRepository(Preference).findOne({ userId });
return preferences ? right(preferences.preferenceMap) : left(new HttpResponseNotFound({ code: 404, message: 'Could not find preferences' }));
}
我想像这样在另一个文件中调用这个函数:
const preferenceMapAsJsonStringOrError: Either<HttpResponseNotFound, string> = await this.preferenceService.getPreferencesForUserId(userId);
const response: HttpResponseOK | HttpResponseNotFound = pipe(preferenceMapAsJsonStringOrError, fold(
e => e,
r => new HttpResponseOK(r)
));
response.setHeader('content-type', 'application/json');
return response;
这基本上是我在 Scala 中的做法。 (除了 fold 是 Either 类型的方法,而不是独立函数 - 所以这里我使用 pipe 帮助器)
问题是,我从 ts-server 收到一个错误:
Type 'HttpResponseOK' is missing the following properties from type 'HttpResponseNotFound': isHttpResponseNotFound, isHttpResponseClientError
和
node_modules/fp-ts/lib/Either.d.ts:129:69
129 export declare function fold<E, A, B>(onLeft: (e: E) => B, onRight: (a: A) => B): (ma: Either<E, A>) => B;
~~~~~~~~~~~
The expected type comes from the return type of this signature.
我可以通过一种更为迫切的方式来解决这个问题:
const preferenceMapAsJsonStringOrError: Either<HttpResponseNotFound, string> = await this.preferenceService.getPreferencesForUserId(userId);
if (isLeft(preferenceMapAsJsonStringOrError)) {
return preferenceMapAsJsonStringOrError.left;
}
const response = new HttpResponseOK(preferenceMapAsJsonStringOrError.right);
response.setHeader('content-type', 'application/json');
return response;
但那时我几乎失去了使用 Either 的好处。
【问题讨论】:
-
TS 的工作方式(以及折叠签名的编写方式)你不会在那里得到统一,在这里看到一个非常相似的讨论:github.com/gcanti/fp-ts/pull/945
-
如果我只想要值或错误,那么
fold不适合使用吗? -
在下面起草了一个答案,如果有帮助请告诉我
-
是的,昨天我坐下来思考的越多,我就越意识到 OF COURSE
fold期望同质类型。我不确定我在想什么。谢谢!
标签: typescript fp-ts