diff --git a/crates/napi/src/js_values/mod.rs b/crates/napi/src/js_values/mod.rs index 1fd72bc2..ca1ff8c4 100644 --- a/crates/napi/src/js_values/mod.rs +++ b/crates/napi/src/js_values/mod.rs @@ -153,6 +153,18 @@ macro_rules! impl_js_value_methods { unsafe { JsUnknown::from_raw_unchecked(self.0.env, self.0.value) } } + pub fn coerce_to_bool(self) -> Result { + let mut new_raw_value = ptr::null_mut(); + check_status!(unsafe { + sys::napi_coerce_to_bool(self.0.env, self.0.value, &mut new_raw_value) + })?; + Ok(JsBoolean(Value { + env: self.0.env, + value: new_raw_value, + value_type: ValueType::Boolean, + })) + } + pub fn coerce_to_number(self) -> Result { let mut new_raw_value = ptr::null_mut(); check_status!(unsafe { @@ -190,7 +202,6 @@ macro_rules! impl_js_value_methods { } #[cfg(feature = "napi5")] - pub fn is_date(&self) -> Result { let mut is_date = true; check_status!(unsafe { sys::napi_is_date(self.0.env, self.0.value, &mut is_date) })?; diff --git a/examples/napi-compat-mode/__test__/env.spec.ts b/examples/napi-compat-mode/__test__/env.spec.ts index 2c603659..1cf61182 100644 --- a/examples/napi-compat-mode/__test__/env.spec.ts +++ b/examples/napi-compat-mode/__test__/env.spec.ts @@ -16,3 +16,14 @@ test('should be able to throw syntax error', (t) => { t.is((e as SyntaxError).message, msg) } }) + +test('should be able to coerceToBool', (t) => { + t.true(bindings.coerceToBool(true)) + t.true(bindings.coerceToBool(1)) + t.true(bindings.coerceToBool({})) + t.true(bindings.coerceToBool(Symbol())) + t.false(bindings.coerceToBool(0)) + t.false(bindings.coerceToBool(undefined)) + t.false(bindings.coerceToBool(null)) + t.false(bindings.coerceToBool(NaN)) +}) diff --git a/examples/napi-compat-mode/src/env.rs b/examples/napi-compat-mode/src/env.rs index e71b3eb3..0fb83d59 100644 --- a/examples/napi-compat-mode/src/env.rs +++ b/examples/napi-compat-mode/src/env.rs @@ -53,6 +53,12 @@ pub fn throw_syntax_error(ctx: CallContext) -> Result { ctx.env.get_undefined() } +#[js_function(1)] +fn coerce_to_bool(ctx: CallContext) -> Result { + let arg: JsUnknown = ctx.get(0)?; + arg.coerce_to_bool() +} + pub fn register_js(exports: &mut JsObject) -> Result<()> { exports.create_named_method("instanceof", instanceof)?; exports.create_named_method("isTypedarray", is_typedarray)?; @@ -61,5 +67,6 @@ pub fn register_js(exports: &mut JsObject) -> Result<()> { exports.create_named_method("castUnknown", cast_unknown)?; exports.create_named_method("getEnvVariable", get_env_variable)?; exports.create_named_method("throwSyntaxError", throw_syntax_error)?; + exports.create_named_method("coerceToBool", coerce_to_bool)?; Ok(()) }