I wish to check if a variable is a valid Google App Script Enum type.
function myFunc(BORDER_COLOR) {
if (typeof BORDER_COLOR !== "Enum") { // This does not work
// do something for this exception
}
// rest of the function
}
I use typeof
and instanceof
to check it. But something strange happens. The Enum
is an object. But it is not an instance of Object. This contradicts my understandings.
- I suppose all primitive types (string, boolean, etc.) are non-objects.
- I suppose all non-primitive (Array, user-defined types, etc.) types are objects.
- (Why?)
.
Logger.log(typeof SpreadsheetApp.BorderStyle.SOLID); // object
Logger.log(SpreadsheetApp.BorderStyle.SOLID instanceof Object); // false <-- unexpected
Logger.log("");
var value = "text";
Logger.log(typeof value); // string
Logger.log(value instanceof Object); // false
Logger.log("");
var value = new String("text");
Logger.log(typeof value); // object
Logger.log(value instanceof Object); // true
Logger.log("");
Logger.log(Array instanceof Object); // true
Logger.log(Object instanceof Object); // true
Added:
var value = 123;
Logger.log(typeof value); // number
Logger.log(TYPEOF(value)); // number
Logger.log(value instanceof Object); // false
Logger.log("");
var value = [];
Logger.log(typeof value); // object
Logger.log(TYPEOF(value)); // Array[0]
Logger.log(value instanceof Object); // true
Logger.log("");
var value = {};
Logger.log(typeof value); // object
Logger.log(TYPEOF(value)); // Object
Logger.log(value instanceof Object); // true
Logger.log("");
function TYPEOF(value) {
if (typeof value !== 'object') // not an object, it is a primitive type
return typeof value;
var details = '';
if (value instanceof Array) { // if this is an object, may be this is an Array
details += '[' + value.length + ']';
if (value[0] instanceof Array)
details += '[' + value[0].length + ']';
}
var className = value.constructor ? value.constructor.name : value.constructor; // if this is not an Array, get the (tailor-made) constructor name
return className + details;
}