I was introduced to Rust in 2018 and has been enamored since. Rust is a system programming language, much like C++. Unlike C++ though, being relatively new, its language design is more modern and sophisticated. Writing with can feel more like writing TypeScript or Haskell. Not surprising since, despite being a language with a very minimum runtime and no GC, it derives many principles of functional programming such as immutability, type inference, higher-order functions, pattern-matching, etc. Over the course of tinkering things with Rust, I realized that writing Rust code makes me a better coder in other languages. This article will describe how my attempt to push the best in Rust’s language design into TypeScript, my main language, without altering the language itself.

Getting Rid of Exceptions

The first thing that strikes me the first time I learnt Rust is that there are no straightforward to write exception-like code in Rust. For someone used to exceptions after using many languages like C++, Java, JavaScript and TypeScript, this seems like an incomplete language. But Rust’s lack of straightforward exception-like is actually thought out in advance.

Exceptions feel neat the first time you understand it. A thrown exception skips code execution into the catch block. By doing that you can ignore the rest of code in the function. The rest of the code in the function represents positive case, which may seem irrelevant when an error happens. Here’s a piece of code:

function foo(someNumber: number) {
  if (someNumber === 0) {
    throw new Error("Error: foo");
  }
  return someNumber + 1;
}
function bar(someNumber: number) {
  return foo(someNumber) + 1;
}
function baz(someNumber: number) {
  return bar(someNumber) + 1;
}
baz(0);

When baz is called it will throw an uncaught exception. By reading the code you know that foo throws an Error. Debugging this snippet is a piece of cake, right?

Now let’s see another snippet. In the snippet below you are importing a function that can throw exception.

import { callMe } from "somePackage";

try {
  // This line may throws an error
  callMe();
} catch (exception) {
  // This line may unexpectedly throws an error again
  // if error turns out a nullish value
  // Uncaught TypeError: Cannot read property 'message' of undefined
  console.error(exception.message);
}

#rust #typescript #programming #developer #web-development

From Rust to TypeScript
3.35 GEEK