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.
JavaScript
x
11
11
1
let myVar
2
3
if (something) {
4
myVar = { someKey: someValue }
5
} else {
6
myVar = new Response( )
7
}
8
9
// check if myVar is a Response or an object...
10
11
Advertisement
Answer
You can use the instanceOf
operator for this purpose:
JavaScript
1
11
11
1
something = false
2
let myVar
3
4
if (something) {
5
myVar = { someKey: someValue }
6
} else {
7
myVar = new Response()
8
}
9
10
11
console.log('IsResponse:', myVar instanceof Response)
JavaScript
1
1
1
.as-console-wrapper { max-height: 100% !important; }