Skip to content

Instantly share code, notes, and snippets.

@MichaelDimmitt
Last active December 20, 2020 19:22
Show Gist options
  • Save MichaelDimmitt/0d6b885ab4d6c5be0705df7c604c7c1a to your computer and use it in GitHub Desktop.
Save MichaelDimmitt/0d6b885ab4d6c5be0705df7c604c7c1a to your computer and use it in GitHub Desktop.
Checking types in javascript.md

https://stackoverflow.com/a/332445/5283424

function a() { this.foo = 1;}
function b() { this.bar = 2; }
b.prototype = new a(); // b inherits from a
var f = new b();
function type(obj){
    return Object.prototype.toString.call(obj).match(/\s\w+/)[0].trim()
}
console.log({ arr: type([]), str: type("sadhs"), classCheck: f })
// output: {arr: "[object Array]", str: "[object String]", classCheck: "[object Object]"}
// output: 
const type = (obj) => obj.constructor.name
console.log({ arr: type([]), str: type("sadhs"), classCheck: type(f) })

// output: {arr: "Array", str: "String", classCheck: type(b)}
// output: {arr: "Array", str: "String", classCheck: "a"}

Through these methods the inferred type can be discovered

There is more complex typechecking, my prefered simple method being: obj.constructor.name

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment