is-what icon indicating copy to clipboard operation
is-what copied to clipboard

the isPlainObject can be improved because it has missed Object.create(null)

Open aswind7 opened this issue 1 year ago • 2 comments

image

it can be this:

export function isPlainObject(payload: any): payload is PlainObject {
  if (getType(payload) !== 'Object') return false
  const prototype = Object.getPrototypeOf(payload)
  if (prototype === null) return true
  return prototype.constructor === Object && prototype === Object.prototype
}

aswind7 avatar Aug 17 '23 05:08 aswind7

export function isPlainObject(payload: any): payload is PlainObject {
  if (getType(payload) !== 'Object') return false
  const prototype = Object.getPrototypeOf(payload)

  // Fix
  if (prototype === null) return true;

  return !!prototype && prototype.constructor === Object && prototype === Object.prototype
}

R00T80Y avatar Feb 06 '24 19:02 R00T80Y

I find in test this. Why?

expect(isPlainObject(Object.create(null))).toEqual(false)

R00T80Y avatar Feb 07 '24 22:02 R00T80Y

isPlainObject is opinionated. I want it to only match objects created with regular object constructor. Eg. const obj = {} If you don't like my interpretation of isPlainObject you can use isAnyObject, which will better fit your use-case.

mesqueeb avatar Jun 23 '24 02:06 mesqueeb