One that I love is `Option::ok_or` (or `Option::ok_or_else` if you like). It takes an Option and converts it to an error. With the try macro (?) it makes Option a lot easier to use. Compare:
function parseFile(file: File | null) {
if (file === null) {
throw new Error("File must exist");
}
// TS now infers as File
}
to: fn parse_file(file: Option<File>) {
let file = file.ok_or(Error::new("File must exist"))?;
}
Likewise if you want to apply a function to an Option if it is Some and pass along None otherwise, you can use `Option::map`: fn parse_file(file: Option<File>) {
let parse_result = file.map(|f| parse(f));
}
Indeed it's a little interesting how libraries have adopted paradigms beyond the language. React is extremely expression based, but that makes for a clunky combo with JS' primarily statement based control flow. You see this in React developers' reliance on ternary operators and short circuiting for control flow in JSX.Of course this just JavaScript being a classical imperative language. Not much to do about that.