-
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathobject-has-own.ts
More file actions
31 lines (24 loc) · 974 Bytes
/
object-has-own.ts
File metadata and controls
31 lines (24 loc) · 974 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
A strongly-typed version of `Object.hasOwn()` that narrows the object type.
This function performs __object narrowing__ for own properties only - it adds the checked property to the object's type, allowing safe property access. Does not check the prototype chain.
Unlike `objectHasIn` (includes inherited) and `keyIn` (key narrowing), this narrows the _object_ type to include only own properties.
@example
```
import {objectHasOwn} from 'ts-extras';
const data: unknown = {foo: 1};
if (objectHasOwn(data, 'foo')) {
// `data` is now: unknown & {foo: unknown}
console.log(data.foo); // Safe access to own property
}
objectHasOwn({}, 'toString');
//=> false (inherited property, not own)
```
@category Improved builtin
@category Type guard
*/
export function objectHasOwn<ObjectType, Key extends PropertyKey>(
object: ObjectType,
key: Key,
): object is (ObjectType & Record<Key, unknown>) {
return Object.hasOwn(object as Record<PropertyKey, unknown>, key);
}