-
|
This is like a basic question, but it surprisingly doesn't seem to have an obvious answer. There's good usage documentation, but… it's more like "JavaScript usage", not "TypeScript usage" if you know what I mean, despite being a TypeScript lib. So, I'm just starting up with the lib, and my older code had: export type ErrorOr<T> = { isError: true; error: string } | { isError: false; val: T };I am replacing it to seemingly obvious: export type ErrorOr<T> = Either<string, T>;And I get shared/Utils.ts:9:26 - error TS2709: Cannot use namespace 'Either' as a type.
9 export type ErrorOr<T> = Either<string, T>;Navigating to the sources shows that there're types |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
|
Found an answer: turns out, Solution here: export type ErrorOr<T> = Either.Either<string, T>;Yeah, it is inconvenient to have to type UPD: oh, here's a funny thing for you: turns out, the above isn't entirely correct, because in the library right values are left and left values are right. Leaving out the fix as an exercise to the reader. |
Beta Was this translation helpful? Give feedback.
-
|
In Effect-TS, import { Effect, Either } from "effect";
// Option 1: Effect<A, E> (preferred in Effect-TS v3)
// The Either is implicit: Effect succeeds with A or fails with E
const computation: Effect.Effect<number, Error> = Effect.try({
try: () => parseInt("42"),
catch: (e) => new Error(`Parse failed: ${e}`),
});
// Option 2: Explicit Either type
import { Either } from "effect";
const divide = (a: number, b: number): Either.Either<number, string> => {
if (b === 0) return Either.left("Division by zero");
return Either.right(a / b);
};
// Convert Either to Effect
const asEffect = Effect.fromEither(divide(10, 2));
// Convert Effect to Either (suspending the fiber)
const asEither: Either.Either<number, Error> = Effect.runSyncEither(computation);The v3 idiom — use Effect directly, not Either, for most cases: import { Effect, pipe } from "effect";
// Chain operations that can fail
const program = pipe(
Effect.succeed(10),
Effect.flatMap((n) => n === 0
? Effect.fail(new Error("Zero!"))
: Effect.succeed(n * 2)
),
Effect.map((n) => `Result: ${n}`),
Effect.catchAll((e) => Effect.succeed(`Error: ${e.message}`)),
);
// Run it
const result = Effect.runSync(program);
// "Result: 20"When to use Either explicitly:
The shift from fp-ts's |
Beta Was this translation helpful? Give feedback.
Found an answer: turns out,
Eitheris simultaneously a module and a type. So the type does exist, it's just declared elsewhere.Solution here:
Yeah, it is inconvenient to have to type
Eithertwice, you might want to redefine ittype TEither<E,V> = Either.Either<E,V>;or some such.UPD: oh, here's a funny thing for you: turns out, the above isn't entirely correct, because in the library right values are left and left values are right. Leaving out the fix as an exercise to the reader.