mesqueeb / is-what

JS type check (TypeScript supported) functions like `isPlainObject() isArray()` etc. A simple & small integration.
https://mesqueeb.github.io/is-what/
MIT License
185 stars 20 forks source link

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

Closed aswind7 closed 5 months ago

aswind7 commented 1 year ago
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
}
R00T80Y commented 9 months ago
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 commented 9 months ago

I find in test this. Why?

expect(isPlainObject(Object.create(null))).toEqual(false)
mesqueeb commented 5 months ago

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.