Skip to main content

Discovering the Datatype of a Value with %GetTypeOf()

Discovering the Datatype of a Value with %GetTypeOf()

You can use the %GetTypeOf() method to get the datatype of a dynamic entity member. A dynamic object property or array element can have any one of following datatypes:

  • An object datatype:

    • array — a dynamic array reference

    • object — a dynamic object reference

    • oref — a reference to an object that is not a dynamic entity

  • A literal value:

    • number — a canonical numeric value

    • string — a string literal or an expression that evaluates to a string literal

  • A JSON literal:

    • boolean — a JSON literal true or false

    • null — a JSON literal null

  • No datatype:

    • unassigned — the property or element exists, but has no assigned value.

Using %GetTypeOf with objects

When you use this method with an object, the argument is the name of the property. For example:

   set dynobj={"prop1":123,"prop2":[7,8,9],"prop3":{"a":1,"b":2}}
   set iter = dynobj.%GetIterator()
   while iter.%GetNext(.name) {write !,"Datatype of "_name_" is "_(dynobj.%GetTypeOf(name))}

Datatype of prop1 is number
Datatype of prop2 is array
Datatype of prop3 is object
Using %GetTypeOf with arrays

When you use this method with an array, the argument is the index of the element. The following example examines a sparse array, where element 2 does not have an assigned value. The example uses a for loop because %GetNext() would skip the unassigned element:

   set dynarray = [12,34]
   set dynarray."3" = "final"
   write dynarray.%ToJSON()
[12,34,null,"final"]

   for index = 0:1:3 {write !,"Datatype of "_index_" is "_(dynarray.%GetTypeOf(index))}
Datatype of 0 is number
Datatype of 1 is number
Datatype of 2 is unassigned
Datatype of 3 is string
Distinguishing between array or object and oref

The datatype of a dynamic entity will be either array or object. An InterSystems IRIS object that is not a dynamic entity will be datatype oref. In the following example, each property of object dyn is one of these three datatypes. Property dynobject is class %DynamicObjectOpens in a new tab, property dynarray is %DynamicArrayOpens in a new tab, and property streamobj is %Stream.GlobalCharacterOpens in a new tab:

   set dyn={"dynobject":{"a":1,"b":2},"dynarray":[3,4],"streamobj":(##class(%Stream.GlobalCharacter).%New())}
   set iterator=dyn.%GetIterator()
   while iterator.%GetNext(.key,.val) { write !, "Datatype of "_key_" is: "_dyn.%GetTypeOf(key) }

Datatype of dynobject is: object
Datatype of dynarray is: array
Datatype of streamobj is: oref

FeedbackOpens in a new tab