What is the best way to achieve Rust question mark operator-like behavior #203
-
Thank you for the great library! For now I settled on
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
Great question! There isn’t really any much better translation than that, because JS doesn’t have native pattern matching. Strictly speaking, you want to do roughly this so that you can get a new error of the correct type, rather than doing an unsafe cast (TS playground): import { Result } from 'true-myth/result';
function demoEarlyReturn(result: Result<string, Error>): Result<number, Error> {
if (result.isErr()) {
return Result.err(result.error);
}
const { value } = result;
return Result.ok(value.length);
} This isn’t great in performance-sensitive code, given the extra allocation… but the unfortunate reality is that our One thing this has me thinking on is the value of some method that would allow you to take an |
Beta Was this translation helpful? Give feedback.
Great question! There isn’t really any much better translation than that, because JS doesn’t have native pattern matching. Strictly speaking, you want to do roughly this so that you can get a new error of the correct type, rather than doing an unsafe cast (TS playground):
This isn’t great in performance-sensitive code, given the extra allocation… but the unfortunate reality is that our
Maybe
andResult
aren’t great in performa…