Eduard
Eduard

Reputation: 9185

Convert string name of JS Object to instance of JS Object

I have a function, which receives 2 params: a variable, and a string representation of a data type ('String', 'Object' etc):

function typeChecker(variable, dataType) {
    // checks type, returns true or false
}

I want to convert the second parameter to a constructor, so that this expression does not throw an error:

variable instanceof 'Date'

Question: Is it possible to convert any of these:

'String'
'Date'
'Object'

To these:

String
Date
Object

Upvotes: 1

Views: 94

Answers (2)

apsillers
apsillers

Reputation: 115970

Those constructors all happen to be members of the global object (either window in the browser or global in Node.js), so you could do one of

variable instanceof window['Date']
variable instanceof global['Date']

If your constructor does not exist as a member o the global object, you can check if any prototype in the value's prototype chain is associated with a constructor whose name matches the desired string:

function checkIfValueIsOfTypeName(value, typeName) {
    while(value = Object.getPrototypeOf(value)) {
        if(value.constructor && value.constructor.name === typeName) {
            return true;
        }
    }
    return false;
}

This is more or less how instanceOf operates internally, except instanceOf directly compares constructor to the right-hand value, instead of comparing its name to a string, which is what you want to do.

Upvotes: 3

regex
regex

Reputation: 101

You can use typeof

console.log(typeof 10);
// output: "number"

console.log(typeof 'name');
// output: "string"

console.log(typeof false);
// output: "boolean"

Upvotes: 0

Related Questions