Skip to content

Function: hasOwnProperty()

hasOwnProperty(val, key): key is never

Safely checks if an object has a property as its own (not inherited). This is a safer alternative to obj.hasOwnProperty() which can fail if the object doesn't have Object.prototype in its chain.

Parameters

val

object

The object to check

key

The property key to check for

string | symbol

Returns

key is never

True if the object has the property as its own, with type narrowing

Example

typescript
const obj = { name: 'John', age: 30 }

if (hasOwnProperty(obj, 'name')) {
  // TypeScript knows obj.name exists
  console.log(obj.name) // 'John'
}

// Safe even with objects that don't inherit from Object.prototype
const nullObj = Object.create(null)
nullObj.prop = 'value'
console.log(hasOwnProperty(nullObj, 'prop')) // true

Released under the MIT License.