TypeScript and Rust, side by side
Shapes just by having the right members.interface Shape {
area(): number;
name(): string;
}
function largest(shapes: Shape[]): string | undefined {
let best: Shape | undefined;
for (const s of shapes) if (!best || s.area() > best.area()) best = s;
return best?.name();
}
// No "implements" needed: any value with the right members is a Shape.
const square = { area: () => 9, name: () => "square" };
const rect = { w: 2, h: 5, area() { return this.w * this.h; }, name: () => "rect" };
console.log(largest([square, rect]), largest([]));impl blocks make both structs Shapes; total_area is generic, and largest takes trait objects.trait Shape {
fn area(&self) -> u32;
fn name(&self) -> &str;
}
struct Square { side: u32 }
struct Rect { w: u32, h: u32 }
impl Shape for Square {
fn area(&self) -> u32 { self.side * self.side }
fn name(&self) -> &str { "square" }
}
impl Shape for Rect {
fn area(&self) -> u32 { self.w * self.h }
fn name(&self) -> &str { "rect" }
}
fn total_area<T: Shape>(items: &[T]) -> u32 {
items.iter().map(|s| s.area()).sum()
}
fn largest(shapes: &[Box<dyn Shape>]) -> Option<&str> {
shapes.iter().max_by_key(|s| s.area()).map(|s| s.name())
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Square { side: 3 }), Box::new(Rect { w: 2, h: 5 })];
println!("{:?} {}", largest(&shapes), total_area(&[Square { side: 2 }, Square { side: 1 }]));
}| TypeScript | Rust |
|---|---|
Any object with area() and name() is a Shape. | Only a type with impl Shape for T is a Shape; a method with the same name is not enough. |
function f<T extends Shape>(x: T) | fn f<T: Shape>(x: &T), compiled separately for each concrete T. |
A Shape[] can hold any mix of shapes. | Mixed values need Vec<Box<dyn Shape>>, dispatched at runtime. |
implements is optional documentation. | The impl block is the implementation; without it the type has none of the trait's methods. |
Understand it
TypeScript interfaces are structural. The object literals in the example have no implements clause, yet both are Shapes because they have area and name. Rust traits are nominal: Square satisfies Shape only after impl Shape for Square { ... }, and an inherent method with the same name does not count. That is the E0277 in the practice code, the trait bound Square: Shape is not satisfied.
A trait bound plays the role of <T extends Shape>. fn total_area<T: Shape>(items: &[T]) is generic: the compiler generates a separate copy for each concrete T it is used with, and the calls are dispatched statically. Every item in that slice must be the same T, so it cannot hold a square and a rectangle together.
For a mixed collection, the counterpart of an array of interface values, use trait objects: Vec<Box<dyn Shape>>. Each element is a pointer to some type that implements Shape plus a table of its methods, and calls are dispatched at runtime, which is how every JavaScript method call works anyway. Neither form is automatically faster: generics can grow code size, and trait objects add an indirection.
Traits cover other TypeScript patterns too. Default methods replace a shared base class, impl Display for T replaces toString, and implementing a standard trait such as PartialOrd plugs your type into existing generic code. You may implement your own trait for a foreign type such as u32, but not a foreign trait for a foreign type.
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.
trait Shape {
fn area(&self) -> u32;
}
struct Square {
side: u32,
}
impl Square {
fn area(&self) -> u32 {
self.side * self.side
}
}
fn print_area<T: Shape>(shape: &T) {
println!("{}", shape.area());
}
fn main() {
print_area(&Square { side: 3 });
}Try it
Port the TypeScript code shown at the top of solution.rs. Implement Priced for Book and for Coffee (250 cents plus 50 per size step, labelled coffee), write the generic total, and write cheapest over trait objects, returning the label of the first cheapest item as the TypeScript loop does. In the Crabrix app, open the compiler lab and complete the supplied code in solution.rs. The reading question is a separate exercise.
What success looks like: The local compiler accepts the changed solution and the separate verification harness passes every case, including an empty list and a tie for the cheapest item. Printing a success message alone does not complete this lab.
Check your understanding
Which signature lets one call handle a list that mixes Book and Coffee values?
Reveal the answer
fn total<T: Priced>(items: &[T]) -> u64fn total(items: &[Box<dyn Priced>]) -> u64fn total(items: &[impl Priced]) -> u64
A generic type parameter, written either way, is one concrete type per call. A slice of Box<dyn Priced> holds different types behind one trait.
Go deeper
Common misconception: “If Square has an area method, it can be passed wherever a Shape is expected, as in TypeScript.”
Rust checks trait implementations, not shapes. Write impl Shape for Square and put the method inside that block.
- Find the impls:
SquareandRecteach get animpl Shapeblock. Without them, neither could be passed tototal_areaor boxed as adyn Shape. - Compare the two calls:
total_area(&[Square { side: 2 }, Square { side: 1 }])uses one concrete type.largest(&shapes)walks boxes that point to different types. - Compare with evidence: Run it:
Some("rect") 5. Trytotal_area(&[Square { side: 2 }, Rect { w: 1, h: 1 }])and read the mismatched types error.
Transfer challenge: Add a default method fn describe(&self) -> String { format!("{} of area {}", self.name(), self.area()) } to Shape, call it on both shapes, then override it for Rect only.
Connections
- Mutating arguments vs borrowing: Shared and mutable borrows
- try/catch vs Result: Errors as Result values

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 interfaces vs traits (courseId "rust-for-nodejs-developers", lessonId "node-interfaces-to-traits") Link: https://crabrix.com/learn/rust-for-nodejs-developers/node-interfaces-to-traits/ Goal: A type implements a trait only through an explicit impl; use a generic bound for static dispatch over one type and dyn Trait for a collection of mixed types. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-nodejs-developers/node-interfaces-to-traits) 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.