Objects.hasProperty()

Syntax

function hasProperty(source: unknown, propertyName: string | number | symbol, type?: TypeofResult | Constructor): boolean

Checks if an object contains a property by the specified name and optionally type.

Parameters
source

The value to check for presence of the property. Accepts any type.

functionName

The name of the property to check for.

type Optional

If passed, hasProperty() returns true only if the property value matches this type. Possible values include any result of the typeof operator as well as any constructor (like Date).

Example

import { Objects } from 'potence';

const object: unknown = { ... };

if (Objects.hasProperty(object, 'count', 'number')) {
    object.count++;  // no error
}

Remarks

This function is a type guard. When used in an if condition, this function will therefore allow you to access source[propertyName] without any TypeScript errors. Note that, unless you specify type, the property’s type will be unknown.

This function is particularly useful when defining custom type guards, though it is generally recommended to use Objects.structure() instead.

Compare with Objects.hasFunction(), which can check for the presence of functions with a certain number of arguments.

Note: For the sake of simplicity, the above function signature is an abridged version of the function’s real signature. To ensure proper TypeScript typing—especially in regards to the return type—a slightly more complex function signature is needed than what is shown here.