Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

isInternalEntity: Assert the value is an object #117

Merged
merged 3 commits into from
Sep 10, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/utils/isInternalEntity.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { InternalEntity, InternalEntityProperty } from '../glossary'
import { isObject } from './isObject'

/**
* Determines if the given object is an internal entity.
* Returns true if the given value is an internal entity object.
*/
export function isInternalEntity(
value: Record<string, any>,
): value is InternalEntity<any, any> {
return (
value &&
isObject(value) &&
InternalEntityProperty.type in value &&
InternalEntityProperty.primaryKey in value
)
Expand Down
6 changes: 6 additions & 0 deletions src/utils/isObject.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/**
* Returns true if the given value is a plain Object.
*/
export function isObject(value: any): value is Record<string, any> {
Copy link
Member Author

@kettanaito kettanaito Sep 8, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using unknown is more suitable here, but there have been some issues with adopting unknown for our TypeScript users in the past. I'd migrate from any to unknown as a separate, carefully released change.

return value != null && typeof value === 'object' && !Array.isArray(value)
}
20 changes: 20 additions & 0 deletions test/utils/isObject.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { isObject } from '../../src/utils/isObject'

it('returns true given an empty object', () => {
expect(isObject({})).toEqual(true)
})

it('returns true given an object with values', () => {
expect(isObject({ a: 1, b: ['foo'] })).toEqual(true)
})

it('returns false given falsy values', () => {
expect(isObject(undefined)).toEqual(false)
expect(isObject(null)).toEqual(false)
expect(isObject(false)).toEqual(false)
})

it('returns false given an array', () => {
expect(isObject([])).toEqual(false)
expect(isObject([{ a: 1 }])).toEqual(false)
})