-
-
Notifications
You must be signed in to change notification settings - Fork 15.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #4620 from reduxjs/is-action-predicate
Add isAction type predicate
- Loading branch information
Showing
4 changed files
with
36 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
import { Action } from '../types/actions' | ||
import isPlainObject from './isPlainObject' | ||
|
||
export default function isAction(action: unknown): action is Action<string> { | ||
return ( | ||
isPlainObject(action) && | ||
'type' in action && | ||
typeof (action as Record<'type', unknown>).type === 'string' | ||
) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import isAction from '@internal/utils/isAction' | ||
|
||
describe('isAction', () => { | ||
it('should only return true for plain objects with a string type property', () => { | ||
const actionCreator = () => ({ type: 'anAction' }) | ||
class Action { | ||
type = 'totally an action' | ||
} | ||
const testCases: [action: unknown, expected: boolean][] = [ | ||
[{ type: 'an action' }, true], | ||
[{ type: 'more props', extra: true }, true], | ||
[{ type: 0 }, false], | ||
[actionCreator(), true], | ||
[actionCreator, false], | ||
[Promise.resolve({ type: 'an action' }), false], | ||
[new Action(), false], | ||
['a string', false] | ||
] | ||
for (const [action, expected] of testCases) { | ||
expect(isAction(action)).toBe(expected) | ||
} | ||
}) | ||
}) |