How to check if object is Immutable?

Immutable object can be an instance of:

  • Immutable.List
  • Immutable.Map
  • Immutable.OrderedMap
  • Immutable.Set
  • Immutable.OrderedSet
  • Immutable.Stack

There is an open ticket to improve the API which is on the roadmap for 4.0. Until this is implemented, I suggest you use Immutable.Iterable.isIterable() (docs).

Using instanceof is not reliable (e. g. returns false when different modules use different copies of Immutable.js)


I have learned that using instanceof to determine wether object is Immutable is unsafe:

Module A:

var Immutable = require('immutable');
module.exports = Immutable.Map({foo: "bar});

Module B:

var Immutable = require('immutable');
var moduleA = require('moduleA');
moduleA instanceof Immutable.Map // will return false

Immutable.js API defines the following methods to check if object is an instance of Immutable:

  • Map.isMap()
  • List.isList()
  • Stack.isStack()
  • OrderedMap.isOrderedMap()
  • Set.isSet()
  • OrderedSet.isOrderedSet()

and

  • Iterable.isIterable()

The latter checks if:

True if an Iterable, or any of its subclasses.

List, Stack, Map, OrderedMap, Set and OrderedSet are all subclasses of Iterable.


Immutable.js has isImmutable() function since v4.0.0-rc.1:

 import { isImmutable, Map, List, Stack } from 'immutable';

 isImmutable([]); // false
 isImmutable({}); // false
 isImmutable(Map()); // true
 isImmutable(List()); // true
 isImmutable(Stack()); // true
 isImmutable(Map().asMutable()); // false

If you use one of the previous versions, you can check if object is Immutable this way:

 Immutable.Iterable.isIterable(YOUR_ENTITY)

because all immutables inherit from the Iterable object


And this way you can get to know what type of Immutable Iterable variable is:

const obj0 = 'xxx';
const obj1 = Immutable.fromJS({x: 'XXX', z: 'ZZZ'});
const obj2 = Immutable.fromJS([ {x: 'XXX'}, {z: 'ZZZ'}]);

const types = ['List', 'Stack', 'Map', 'OrderedMap', 'Set', 'OrderedSet'];
const type0 = types.find(currType => Immutable[currType][`is${currType}`](obj0));
const type1 = types.find(currType => Immutable[currType][`is${currType}`](obj1));
const type2 = types.find(currType => Immutable[currType][`is${currType}`](obj2));

console.log(`Obj0 is: ${type0}`); // Obj0 is: undefined
console.log(`Obj1 is: ${type1}`); // Obj1 is: Map
console.log(`Obj2 is: ${type2}`); // Obj2 is: List
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script>