Docs
/
Concepts
/
Function

Function

Defining a JavaScript function is very simple in NAPI-RS. Just a plain Rust fn:

#[napi]
fn sum(a: u32, b: u32) -> u32 {
  a + b
}

The most important thing you should keep in mind is NAPI-RS fn does not support every Rust type. Here is a table to illustrate how JavaScript types map to Rust types when they are fn arguments and return types:

Arguments

Rust TypeJavaScript Type
u32number
i32number
i64number
f64number
boolboolean
Stringstring
Latin1Stringstring
UTF16Stringstring
#[napi(object)] structObject
& struct or &mut structClass instance
serde_json::MapObject
serde_json::Valueunknown
std::collections::HashMapObject
Arrayunknown[]
Vec<T> T must be types in this tableT[]
BufferBuffer
ExternalExternal
Nullnull
Undefined/()undefined
Option<T>T or null
Fn(Arg) ->T Arg and T must be types in this table(arg: Arg) => T
Promise<T>Promise<T>
AbortSignalAbortSignal
JsSymbolSymbol
Int8Array/Uint8Array/Int16Array...TypedArray
BigIntBigInt

Return Type

Rust TypeJavaScript Type
u32number
i32number
i64number
f64number
boolboolean
Stringstring
Latin1Stringstring
UTF16Stringstring
#[napi(object)] structObject
#[napi] structClass
serde_json::MapObject
serde_json::Valueunknown
std::collections::HashMapObject
Arrayunknown[]
Vec<T> T must be types in this tableT[]
BufferBuffer
ExternalExternal
Nullnull
Undefined/()undefined
Option<T>T or null
AsyncTask<Task<JsValue = T>>Promise<T>
JsSymbolSymbol
Int8Array/Uint8Array/Int16Array...TypedArray
BigIntBigInt
i64nBigInt
i128BigInt
u128BigInt