I have a generic utility type called Result for operations that might return a value or might return an error:
export type Result<T, E> =
| {ok: true, value: T}
| {ok: false, err: E};
// Normal use
const r: Result<number, string> = performOperation1();
if (!r.ok) {
reportError(r.err);
return;
}
doSomething(r.values);
If I pass in never for the E type parameter, I know that the ok must be true, but TypeScript doesn't:
const r: Result<number, number> = performOperation2();
doSomething(r.value);
Is there a way to get TypeScript to understand that passing in never here eliminates the error branch?
Note: In this tiny example, performOperation2 could just return number instead of Result. But in my full codebase, all of these "operation" functions conform to an interface, which returns Result.