The World’s Largest Online Community for Developers

'; javascript - Validation check of object? - LavOzs.Com

I am having problem that it is not throwing an error if the payload does not Prop1 OR Prop2

What went wrong?

const payload = {
    Prop3: {
      Field1: 1,
      Field2: 2,

if ((!payload.Prop1 && typeof payload.Prop1 === "object") || (!payload.Prop2 && typeof payload.Prop2 === "object")) {
    throw new Error("Must contain Prop1 or Prop2")

That is because typeof undefined is undefined and not object.

Here Prop1 is undefined and its typeof is not "object" So, your code never satisfies if condition

You could write

(!payload.Prop1 && typeof payload.Prop1 !== "object") || (!payload.Prop2 && typeof payload.Prop2 !== "object")

if you are expecting Prop1 and Prop2 to be objects

(!payload.Prop1 && typeof payload.Prop1 === "object")

returns true if payload does not have Prop1 AND Prop1 is of type object which is not what you want. It should be

(!payload.Prop1 && typeof payload.Prop1 !== "object")