diff --git a/crates/napi/src/bindgen_runtime/js_values/array.rs b/crates/napi/src/bindgen_runtime/js_values/array.rs index f687439e..2b6c2137 100644 --- a/crates/napi/src/bindgen_runtime/js_values/array.rs +++ b/crates/napi/src/bindgen_runtime/js_values/array.rs @@ -1,6 +1,6 @@ use std::ptr; -use crate::{bindgen_prelude::*, check_status, sys, ValueType}; +use crate::{bindgen_prelude::*, check_status, sys, JsObject, Value, ValueType}; pub struct Array { env: sys::napi_env, @@ -69,6 +69,16 @@ impl Array { pub fn len(&self) -> u32 { self.len } + + pub fn coerce_to_object(self) -> Result { + let mut new_raw_value = ptr::null_mut(); + check_status!(unsafe { sys::napi_coerce_to_object(self.env, self.inner, &mut new_raw_value) })?; + Ok(JsObject(Value { + env: self.env, + value: new_raw_value, + value_type: ValueType::Object, + })) + } } impl TypeName for Array { diff --git a/examples/napi/__test__/typegen.spec.ts.md b/examples/napi/__test__/typegen.spec.ts.md index eb49d821..61d797e9 100644 --- a/examples/napi/__test__/typegen.spec.ts.md +++ b/examples/napi/__test__/typegen.spec.ts.md @@ -25,6 +25,7 @@ Generated by [AVA](https://avajs.dev). /** Gets some numbers */␊ export function getNums(): Array␊ export function sumNums(nums: Array): number␊ + export function toJsObj(): object␊ export function readFileAsync(path: string): Promise␊ export function asyncMultiTwo(arg: number): Promise␊ export function bigintAdd(a: bigint, b: bigint): bigint␊ diff --git a/examples/napi/__test__/typegen.spec.ts.snap b/examples/napi/__test__/typegen.spec.ts.snap index 68d623b1..6da8ac63 100644 Binary files a/examples/napi/__test__/typegen.spec.ts.snap and b/examples/napi/__test__/typegen.spec.ts.snap differ diff --git a/examples/napi/index.d.ts b/examples/napi/index.d.ts index 4883f0e7..a747fe77 100644 --- a/examples/napi/index.d.ts +++ b/examples/napi/index.d.ts @@ -15,6 +15,7 @@ export function getWords(): Array /** Gets some numbers */ export function getNums(): Array export function sumNums(nums: Array): number +export function toJsObj(): object export function readFileAsync(path: string): Promise export function asyncMultiTwo(arg: number): Promise export function bigintAdd(a: bigint, b: bigint): bigint diff --git a/examples/napi/src/array.rs b/examples/napi/src/array.rs index 01d5f546..bec01a49 100644 --- a/examples/napi/src/array.rs +++ b/examples/napi/src/array.rs @@ -1,3 +1,5 @@ +use napi::{Env, JsObject}; + #[napi] pub fn get_words() -> Vec<&'static str> { vec!["foo", "bar"] @@ -13,3 +15,11 @@ fn get_nums() -> Vec { fn sum_nums(nums: Vec) -> u32 { nums.iter().sum() } + +#[napi] +fn to_js_obj(env: Env) -> napi::Result { + let mut arr = env.create_array(0)?; + arr.insert("a string")?; + arr.insert(42)?; + arr.coerce_to_object() +}