LogoAnchor Docs

Rust to JS Type Conversion

Reference for how Anchor converts between Rust and TypeScript types

This reference shows to converts between Rust and TypeScript types.

Primitive Types

Boolean

RustTypeScriptExample
boolbooleantrue

Numbers

RustTypeScriptExample
u8/u16/u32/i8/i16/i32number99
u64/u128/i64/i128anchor.BNnew anchor.BN(99)
f32/f64number1.0

Strings

RustTypeScriptExample
Stringstring"hello"

Collections

Arrays and Vectors

RustTypeScriptExample
[T; N] (fixed array)Array<T>[1, 2, 3]
Vec<T> (vector)Array<T>[1, 2, 3]

Optional Values

RustTypeScriptExample
Option<T>T | null | undefinednull (None)
42 (Some)

Complex Types

Structs

Rust
// Rust
struct MyStruct {
    val: u16,
}
TypeScript
// TypeScript
type MyStruct = {
  val: number;
};
 
// Example
const instance = { val: 99 };

Enums

Rust
// Rust
enum MyEnum {
    One,
    Two { val: u32 },
    Three(u8, i16),
}
TypeScript
// TypeScript Representations
// Unit variant
const one = { one: {} };
 
// Named variant
const two = {
  two: { val: 99 },
};
 
// Tuple variant
const three = {
  three: [12, -34],
};

Notes

  • Rust integers (u8 through i32) map to JavaScript number
  • Larger integers (u64 and above) use Anchor's BN type for precision
  • Rust's Option<T> maps to TypeScript's union type with null/undefined
  • Structs and enums become JavaScript objects

On this page

Edit on GitHub