Skip to content

Glossary

When learning Rust after writing TypeScript, you frequently run into the question “what is the Rust equivalent of this?” This page is a 1-to-1 reference mapping TypeScript concepts to their Rust counterparts.


TypeScriptRustNotes
stringString / &strString is an owned string; &str is a borrowed string slice
numberi32, f64, u64, etc.Rust requires explicit integer/float sizes
booleanboolidentical
null / undefinedOption<T>represented as None; requires unwrapping
T | nullOption<T>Some(T) or None
T | ErrorResult<T, E>Ok(T) or Err(E)
any(none)Rust has no any type; the closest is Box<dyn Any>
unknown(none)all types are determined at compile time
never!a type that never returns (loop, panic, etc.)
void()unit type
Array<T> / T[]Vec<T>dynamic array
[T, U] (tuple)(T, U)tuple
Record<K, V> / Map<K, V>HashMap<K, V>hash map
Set<T>HashSet<T>hash set
readonly T[]&[T]immutable slice
Generics <T>Generics <T>similar, but Rust requires trait bounds
interface Foo {}trait Foo {}behavior definition
class Foo {}struct Foo {} + impl Foo {}data and methods are separate
Type union A | B | Cenum { A, B, C }Rust enums can carry data

TypeScriptRustNotes
const x = 1let x = 1Rust let is immutable by default
let x = 1let mut x = 1mut is required for mutable variables
const (no reassignment)let (immutable by default)conceptually similar
if / else if / elseif / else if / elseidentical; in Rust, if is an expression
switchmatchRust match is exhaustive and can return values
for...offor x in iteriterator traversal
whilewhileidentical
for...in (key traversal).iter().enumerate()when you need indices
try / catch / finallyResult<T, E> + ? operatorno exceptions; errors are values
throw new Error()return Err(...) / panic!()panic! is unrecoverable
?. (optional chaining).map() / if let Some(x) =Option chaining
?? (nullish coalescing).unwrap_or(default)default value when None

TypeScriptRustNotes
function f(x: number): numberfn f(x: i32) -> i32function declaration
const f = (x) => x + 1|x| x + 1closure
async function f()async fn f()async function
await promise.awaitasync wait
Promise<T>Future<T>async value
Default params f(x = 0)(none; use Option<T> or overloading)default parameters
Rest params ...args(none; use a slice or Vec)variadic arguments
Destructuring { a, b }pattern matching let (a, b) = ...destructuring

TypeScript ConceptRust ConceptNotes
GC (Garbage Collector)Ownership systemcompile-time memory management
Reference (freely passed)Ownership transfer (move)Rust: one owner at a time
Reference (freely shared)Immutable reference &Tmultiple concurrent borrows allowed
(none)Mutable reference &mut Tonly one at a time
(none)Lifetime 'aexplicit validity scope of a reference
Shallow copyClone traitexplicit deep copy
(automatic copy)Copy traitauto-copy for stack types (i32, bool, etc.)
WeakRefWeak<T>prevents reference cycles

TypeScript / Node.jsRustNotes
package.jsonCargo.tomlpackage configuration file
npm / yarn / pnpmcargopackage manager
npmjs.comcrates.iopackage registry
node_modules/~/.cargo/ + target/where dependencies are stored
npm install foocargo add fooadd a dependency
npm run buildcargo buildbuild
npm run build (prod)cargo build --releaseoptimized build
npm testcargo testrun tests
tscrustc (rarely used directly)compiler
tsconfig.jsonCargo.toml + rustfmt.tomlconfiguration
eslintcargo clippylinter
prettierrustfmtformatter
npm workspacesCargo workspacesmonorepo

TypeScriptRustNotes
throw new Error("msg")return Err("msg".into())return an error
try { ... } catch(e) { ... }match result { Ok(v) => ..., Err(e) => ... }handle an error
e instanceof TypeErrormatch e { MyError::Type => ... }distinguish error types
Error subclassingenum MyError { ... } + thiserrorcustom errors
e.messagee.to_string()error message
(none)? operatorerror propagation (without try/catch)
Promise.reject()Err(...)async error

String is an owned string allocated on the heap. &str is a read-only slice that points to a string that already exists somewhere. For function parameters, accepting &str is more flexible; use String only when ownership is required.

fn greet(name: &str) { // &str: borrow and read without owning
println!("Hello, {}!", name);
}
let owned: String = String::from("Alice"); // String: owned
let borrowed: &str = &owned; // &str: borrowed
greet(&owned); // String → &str auto-conversion (Deref coercion)
greet("Bob"); // string literals are also &str

Types that implement the Copy trait (i32, bool, f64, char, etc.) are automatically copied on assignment, leaving the original intact. The Clone trait requires an explicit .clone() call and is used for types with heap data like String or Vec.

let a: i32 = 5;
let b = a; // Copy: a is still valid
let s1 = String::from("hello");
let s2 = s1.clone(); // Clone: s1 is still valid
// let s2 = s1; // this would move s1, making it unusable
MethodBehaviorWhen to use
.unwrap()panic! if no valueprototyping, cases that can’t possibly fail
.expect("msg")panic! with a message if no valuedebugging, when you want a clear failure reason
?propagates the error to the callerproduction code, chained error handling
// unwrap: on failure prints "called unwrap on None"
let x = some_option.unwrap();
// expect: on failure prints the specified message
let x = some_option.expect("there must be a value here");
// ?: propagates the error upward; function return type must be Result
fn parse_config() -> Result<Config, MyError> {
let raw = std::fs::read_to_string("config.toml")?; // returns immediately on error
let config: Config = toml::from_str(&raw)?;
Ok(config)
}
TypePurpose
Box<T>heap allocation, single owner
Rc<T>multiple owners (single thread)
Arc<T>multiple owners (multiple threads)

Box<T> is used to place a type of unknown size on the heap or to simply move ownership to the heap. Rc<T> enables multiple owners via reference counting, but is single-threaded only. Arc<T> is the thread-safe version of Rc<T>, used to share data across threads.

impl Traitdyn Trait
DispatchStatic (static dispatch)Dynamic (dynamic dispatch)
PerformanceCompile-time optimization, fastRuntime vtable lookup, slightly slower
TypeResolved to a single type at compile timeCan be different types at runtime
Return type usagefn f() -> impl Traitfn f() -> Box<dyn Trait>
Storing in a collectionNot possible (same type only)Possible (Vec<Box<dyn Trait>>)
// impl Trait: type is fixed at compile time (fast)
fn make_adder(x: i32) -> impl Fn(i32) -> i32 {
move |y| x + y
}
// dyn Trait: type determined at runtime (flexible)
fn get_shape(kind: &str) -> Box<dyn Shape> {
match kind {
"circle" => Box::new(Circle::new()),
"rect" => Box::new(Rectangle::new()),
_ => panic!("unknown shape"),
}
}

Come back to this page whenever you get stuck on a concept. It’s here to help you quickly find the Rust equivalent of something familiar from TypeScript and keep your momentum going.