Search code examples
javascripttypeof

How to "type check" function parameters?


What's the best way to check the type for objects created by Object.create or literal, for example the following code. I want to make sure the arguments to the function is safe to use. Maybe I shouldn't check the type of arguments, but check whether the properties the function uses are not undefined. But it seems very tedious to do so. What's the best approach, thanks.

var base = {
    name : "abc"
};

var child = Object.create(base);
do_something = function(o) {
    if (typeof(o) === "base") { // will not work
      ...
    }
}

Solution

  • typeof can only return the base type like, object, strirng, number, undefined.

    typeof o === "object"
    

    instanceof can be used if you are inheriting from the base class. Eg here MDN

    function Base() {
      this.name = "abc";
    }
    var child = new Base();
    var a = child instanceof Base;  //true
    

    instance of expects the format <object> insanceof <function>


    You can use isPrototypeOf() when inheriting using Object.create()

    var base = {name; "abc"};
    var child = Object.create(base);
    
    base.isPrototypeOf(child);
    

    More info can be read here: Mozilla Developer Network: isPrototypeOf


    To check if there exists an object o with the attribute name non empty, you can do

    if(typeof o === "object" && typeof o.name !== "undefined")
    

    A shorthand can be used, if name will not hold falsy values like 0

    if(o && o.name)