| I'm a huge fan of strictNullChecks but it is remarkable how much language features contribute towards making non-nullable types ergonomic. For instance Rust has a lot of primitives on Option a lot nicer. 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. |
In fairness, I've done a lot of work in TS and exactly none in Rust, so this is totally biased, but at the very least, it seems like all you're getting in the next examples is two fewer lines of code, in return for assuming that the reader is familiar with 1) `Option<x>` 2) `.ok\_or` 3) the syntax of the third block which I don't remotely get.
Genuine question, how comparable are these things to understanding "File | null" in TS, which I would consider day 1 learning?