Skip to content
Advertisement

Check if variable is a Response object or normal object

Is it possible to check if a variable is a Resonse type object vs a normal object?

I have tried to use typeof, but both cases end in the object. I also tried to do Object.keys(myVar). This gives me an empty array on Response and keys on the object. This could work, but I hope there is a better way to distinguish both.

let myVar

if (something) {
    myVar = { someKey: someValue }
} else {
    myVar = new Response(...)
}

// check if myVar is a Response or an object...

Advertisement

Answer

You can use the instanceOf operator for this purpose:

something = false
let myVar

if (something) {
    myVar = { someKey: someValue }
} else {
    myVar = new Response()
}


console.log('IsResponse:', myVar instanceof Response)
.as-console-wrapper { max-height: 100% !important; }
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement