diff --git a/ReactCommon/jsi/jsi/jsi.cpp b/ReactCommon/jsi/jsi/jsi.cpp index a40fe8664d7bc3..4dfb1a04af2f76 100644 --- a/ReactCommon/jsi/jsi/jsi.cpp +++ b/ReactCommon/jsi/jsi/jsi.cpp @@ -283,6 +283,15 @@ bool Value::strictEquals(Runtime& runtime, const Value& a, const Value& b) { return false; } +bool Value::asBool() const { + if (!isBool()) { + throw JSINativeException( + "Value is " + kindToString(*this) + ", expected a boolean"); + } + + return getBool(); +} + double Value::asNumber() const { if (!isNumber()) { throw JSINativeException( diff --git a/ReactCommon/jsi/jsi/jsi.h b/ReactCommon/jsi/jsi/jsi.h index 816d563cff3c81..d522fa7bb0d280 100644 --- a/ReactCommon/jsi/jsi/jsi.h +++ b/ReactCommon/jsi/jsi/jsi.h @@ -1078,6 +1078,10 @@ class JSI_EXPORT Value { return data_.boolean; } + /// \return the boolean value, or throws JSIException if not a + /// boolean. + bool asBool() const; + /// \return the number value, or asserts if not a number. double getNumber() const { assert(isNumber()); diff --git a/ReactCommon/jsi/jsi/test/testlib.cpp b/ReactCommon/jsi/jsi/test/testlib.cpp index 87dffaa56debed..ef325e9bd2f7e5 100644 --- a/ReactCommon/jsi/jsi/test/testlib.cpp +++ b/ReactCommon/jsi/jsi/test/testlib.cpp @@ -849,6 +849,8 @@ TEST_P(JSITest, ValueTest) { EXPECT_EQ(eval("'str'").getString(rt).utf8(rt), "str"); EXPECT_TRUE(eval("[]").getObject(rt).isArray(rt)); + EXPECT_TRUE(eval("true").asBool()); + EXPECT_THROW(eval("123").asBool(), JSIException); EXPECT_EQ(eval("456").asNumber(), 456); EXPECT_THROW(eval("'word'").asNumber(), JSIException); EXPECT_EQ(