isObject function
Checks whether a value is a non-null object: plain object, array, class instance, date… isRecord accepts plain objects only.
ts
import { isObject } from 'utils';Signature
ts
export function isObject(value: unknown): value is objectParameters
| Name | Description |
|---|---|
value | The value to check. |
Returns
true for any non-null object; false for a function.
Example
ts
isObject([]); // true
isObject(null); // falseTests
Line coverage: 100 %.
- ✅ checks {} as true
- ✅ checks [] as true
- ✅ checks {"x":0} as true
- ✅ checks "1970-01-01T00:00:00.000Z" as true
- ✅ checks null as false
- ✅ checks undefined as false
- ✅ checks "object" as false
- ✅ checks undefined as false
Source
src/guard/is-object.ts (on GitHub)
Used by
isDeepEqual: Checks whether two values are equal at every depth: primitives (NaNequalsNaN), arrays, objects with the same prototype,Date,RegExp,Map,Setand typed arrays.isShallowEqual: Checks whether two values are equal at the first level, withObject.is: skips an update when a new object carries the same values as the previous one.
Source code
ts
/**
* Checks whether a value is a non-null object: plain object, array, class instance, date… `isRecord` accepts
* plain objects only.
*
* @param value - The value to check.
* @returns `true` for any non-null object; `false` for a function.
* @example
* isObject([]); // true
* isObject(null); // false
*/
export function isObject(value: unknown): value is object {
return typeof value === 'object' && value !== null;
}Test file
ts
import { isObject } from './is-object';
class Point {
public readonly x = 0;
}
// Plain function type: calls are not seen as conditions, so any value can be passed.
describe(isObject, () => {
it.for([
[{}, true],
[[], true],
[new Point(), true],
[new Date(0), true],
[null, false],
[undefined, false],
['object', false],
[(): number => 0, false],
] as const)('checks %j as %s', ([value, expected]) => {
expect(isObject(value)).toBe(expected);
});
});Keywords: is, object, guards, function