Rust at a glance · 11 min · free lesson

TypeScript types vs Rust types

TypeScript types are erased and can be bypassed with any or as; Rust types are enforced by rustc, which builds nothing until its diagnostics are fixed.

Core idea

rustc refuses to build a program with a type error: read each diagnostic's code, span and labels, and repair the first causal error before chasing its downstream messages.

TypeScript and Rust, side by side

TypeScript The assertion and any satisfy tsc, and then the runtime adds a string to a number and calls a method on null.
interface User {
  id: number;
  name: string;
}

const raw = '{"id": "42", "name": null}';
const user = JSON.parse(raw) as User; // the assertion is never checked
console.log(typeof user.id, user.id + 1);

const anything: any = user.name;
try {
  console.log(anything.toUpperCase()); // compiles, fails at runtime
} catch (err) {
  console.log((err as Error).message);
}
Rust Outside text becomes a User only through parsing, and each failure says what was wrong.
#[derive(Debug)]
struct User {
    id: u32,
    name: String,
}

fn parse_user(id: &str, name: Option<&str>) -> Result<User, String> {
    let id: u32 = id.parse().map_err(|e| format!("id {id:?}: {e}"))?;
    let name = name.ok_or("name is missing")?.to_string();
    Ok(User { id, name })
}

fn main() {
    println!("{:?}", parse_user("42", Some("ana")));
    println!("{:?}", parse_user("4x2", Some("ana")));
    println!("{:?}", parse_user("42", None));
}
What changes
TypeScriptRust
JSON.parse(raw) as User is never checked at runtime.Text becomes a User only through parsing that returns a Result.
any turns type checking off for a value.There is no any: every value has one concrete type that the compiler knows.
Types are erased before the JavaScript runs.Types shape the compiled code: a u32 is four bytes, and + on it is integer addition.
A tsc error can be ignored, and the emitted JavaScript still runs.rustc builds nothing until every error is fixed.

Understand it

TypeScript checks your code and then erases the types: the JavaScript that runs has no idea a User exists. JSON.parse(raw) as User is a promise to the compiler that nothing verifies, any switches checking off, and a wrong assertion raises no error. In the example, user.id + 1 type-checks as numeric addition and produces the string "421" at runtime.

Rust has no any and no unchecked assertion between unrelated types. A value of type u32 is a u32 in the compiled program; text from outside becomes one only through a step that can fail and says so, such as "42".parse::<u32>(), which returns a Result. Serde's serde_json::from_str::<User> works the same way: a JSON string where the struct expects a number is an Err, not a quietly wrong object. The escape hatches that do exist, as between numeric types and unsafe code, are narrow and visible.

Because rustc refuses to build a program with a type error, reading its diagnostics is a daily skill. Each error has a code such as E0308, a primary span marked with ^^^ under the offending expression, labels such as expected u32, found &str, and often a help: line with a suggestion. rustc --explain E0308 prints a longer explanation with examples. Treat a suggestion as a hint rather than an order: decide first what the program should mean.

Read the errors from the top and repair the first causal one. In the practice code, id is text, so both id + 1 and User { id } fail; the root cause is the missing parse, and once id is a u32 both messages disappear. Patching each later message with a cast or an annotation hides the real mistake and can create new errors further down.

The TypeScript habit, written in Rust

This is how the TypeScript version usually looks on a first attempt in Rust. Predict what rustc says before you read the explanation.

struct User {
    id: u32,
}

fn main() {
    let id = "42";
    let next = id + 1;
    let user = User { id };
    println!("{} {}", user.id, next);
}

Practise this code in Playground ↗

Try it

Compile the practice code and read both errors: the code, the primary span and the labels. Fix only the root cause, compile again and confirm that both messages are gone. Then run rustc --explain E0369.

What success looks like: You fixed both errors with one change, and you can point to the span and label that revealed the root cause.

Check your understanding

For the practice code, rustc reports E0369 at id + 1 and E0308 at User { id }. What do you fix first?

Reveal the answer
  1. The User struct: change its id field to &str
  2. The binding id: both errors start where text is used as a number, so parse it once with "42".parse::<u32>()
  3. Add as u32 at both error sites

Both diagnostics trace back to id being a &str. Parsing it into a u32 removes the root cause, and both messages go away; as cannot convert text at all (E0606).

Go deeper

Common misconception: “as in Rust works like a TypeScript assertion: it tells the compiler to treat a value as another type.”

Rust's as performs a real conversion between compatible primitive types and is rejected for anything else, such as &str to u32 (E0606). Converting outside data is a fallible operation such as parse.

  1. Read the types: User.id is a u32, and parse_user receives text. The only way from one to the other is id.parse(), which returns a Result.
  2. Follow the failures: "4x2" fails in parse, and the error says why; a missing name fails in ok_or. Neither path can produce a half-valid User.
  3. Compare with evidence: Run it: Ok(User { id: 42, name: "ana" }), then an Err naming the invalid digit in "4x2", then Err("name is missing").

Transfer challenge: Call parse_user("-1", Some("ana")) and parse_user("4294967296", Some("ana")), predict both error messages and check them. Then name the JavaScript expression that would have accepted each value without complaint.

Connections

  • Garbage collection vs deterministic drop: Deterministic drop at the end of scope
  • console.log vs println!: Compile-time checked formatting
Side-by-side comparison: the TypeScript version on the left, the Rust version on the right, then 4 rows naming what changes.
TypeScript types vs Rust types: the same task in TypeScript and in Rust, with the differences that matter.
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: TypeScript types vs Rust types (courseId "rust-for-nodejs-developers", lessonId "node-types-are-checked-not-erased")
Link: https://crabrix.com/learn/rust-for-nodejs-developers/node-types-are-checked-not-erased/
Goal: rustc refuses to build a program with a type error: read each diagnostic's code, span and labels, and repair the first causal error before chasing its downstream messages.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-nodejs-developers/node-types-are-checked-not-erased) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.