Skip to content

Improvements to data type test functions on Napi::Value #225

@ebickle

Description

@ebickle

The Napi::Value class contains a number of "Is" functions that tests whether the value is a particular data type. Coverage is spotty for a few scenarios, making certain types of data type tests more complex than they need to be.

I'd like to propose the following additions:

  • bool Napi::Value::IsTypedArrayOf<T>() const;
  • bool Napi::Value::IsInstanceOf<T>() const;
  • bool Napi::Value::IsExternalOf<T>() const;

IsTypedArrayOf

Determine whether the value is a typed array of the specified type.

Example: value.IsTypedArray<uint8_t>().

Without this function, parameter validation of typed arrays is very complex:

  1. Value.IsTypedArray()
  2. Cast value to a TypedArray using Value.As()
  3. Use TypedArray.TypedArrayType() is used to determine the array type.
  4. Use Value.As() is used a second time to cast to the final array type. Far too complex.

IsInstanceOf

Determine whether the value is an object of the specific type.

Example: value.IsInstanceOf<MyClass>();

Currently, determining whether a value is an instance of an 'ObjectWrap' subclass and unwrapping it is complex:

  1. Value.IsObject()
  2. Cast value to an Object using Value.As().
  3. Expose static Napi::FunctionReference constructor property from ObjectWrap subclass as public; note that this violates abstraction principles. Alternately, add an bool IsInstance(Napi::Value) method to the class - but at this point we're re-implementing something node-addon-api should arguably already do for us.
  4. Call Object.InstanceOf(constructor);
  5. Unwrap object.

Napi::Object already has InstanceOf(const Function &constructor) but it suffers from to flaws: 1) Callers need to cast values to an object before using it and 2) a reference to the constructor is needed (private in all samples!) - the C++ type cannot be used.

IsExternalOf

Determines whether the value is an external value of the specified type. Note that there is no Napi::External type; API consumers need to 'jump' directly from a Napi::Value to a Napi::External<T>. There is no way for a caller to determine the type of an external without this function.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions