我正在使用 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 的好处。