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
170 stars 18 forks source link

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

Closed aswind7 closed 1 week ago

aswind7 commented 10 months 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 4 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 4 months ago

I find in test this. Why?

expect(isPlainObject(Object.create(null))).toEqual(false)
mesqueeb commented 1 week 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.