@rbxts/jsnatives



Object.hasOwn

Determines whether an object has a property with the specified name.

Signature

function hasOwn<T>(obj: ReadonlyArray<T>, key: number): boolean
function hasOwn<T>(obj: ReadonlySet<T>, key: T): boolean
function hasOwn<K, T>(obj: ReadonlyMap<K, T>, key: K): boolean
function hasOwn<T extends object>(obj: T, key: keyof T): obj is T & Record<keyof T, NonNullable<T[keyof T]>>

Description

The Object.hasOwn() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). The method is type-aware and works differently based on the object type:

Examples

Object property check

const obj = {a: 1, b: 2, c: 3};
print(Object.hasOwn(obj, "a")); // true
print(Object.hasOwn(obj, "b")); // true
print(Object.hasOwn(obj, "c")); // true
print(Object.hasOwn(obj, "d")); // false

Proxy property check

const proxiedObj = new Proxy({}, {
ownKeys: () => ["a", "b", "c"]
});
print(Object.hasOwn(proxiedObj, "a")); // true
print(Object.hasOwn(proxiedObj, "b")); // true
print(Object.hasOwn(proxiedObj, "c")); // true
print(Object.hasOwn(proxiedObj, "d")); // false

Set value check

const set = new Set([1, 2, 3]);
print(Object.hasOwn(set, 1)); // true
print(Object.hasOwn(set, 2)); // true
print(Object.hasOwn(set, 3)); // true
print(Object.hasOwn(set, 4)); // false

Map key check

const map = new Map([["a", 1], ["b", 2], ["c", 3]]);
print(Object.hasOwn(map, "a")); // true
print(Object.hasOwn(map, "b")); // true
print(Object.hasOwn(map, "c")); // true
print(Object.hasOwn(map, "d")); // false

Array index check

const array = [1, 2, 3];
print(Object.hasOwn(array, 0)); // true
print(Object.hasOwn(array, 1)); // true
print(Object.hasOwn(array, 2)); // true
print(Object.hasOwn(array, 3)); // false