Skip to content

Commit df034e7

Browse files
committed
Adds node utils
1 parent 9723916 commit df034e7

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

packages/utils/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export * from './imports';
2+
export * from './nodes';
23
export * from './jsx';
34
export * from './motions';
45
export * from './comments';

packages/utils/src/nodes.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { ASTNode } from 'jscodeshift';
2+
3+
/**
4+
* The isNodeOfType function uses generics to check if a node of type ASTNode is of a specified type.
5+
* If the check passes, the type of node is narrowed to the expected type, ensuring that the returned type of the function is always correct.
6+
*
7+
* Example:
8+
*
9+
* ```ts
10+
* const isImportSpecifier = isNodeOfType(node, 'ImportSpecifier');
11+
* ```
12+
*/
13+
export const isNodeOfType = <Expected extends ASTNode>(
14+
node: ASTNode,
15+
type: Expected['type'],
16+
): node is Expected => node.type === type;

website/docs/api/codeshift-utils.mdx

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,25 @@ However, it is also available for use outside of this project and compatible wit
1515

1616
`npm install --save-dev @codeshift/utils` or `yarn add -D @codeshift/utils`
1717

18+
## Nodes
19+
20+
### `isNodeOfType`
21+
22+
`isNodeOfType(node, type)`
23+
24+
The `isNodeOfType` function uses generics to check if a node of type `ASTNode` is of a specified type.
25+
If the check passes, the type of node is narrowed to the expected type, ensuring that the returned type of the function is always correct.
26+
27+
**Returns**
28+
29+
`boolean`
30+
31+
**Example**
32+
33+
```jsx
34+
const isImportSpecifier = isNodeOfType(node, 'ImportSpecifier');
35+
```
36+
1837
## Imports
1938

2039
### `hasImportDeclaration`

0 commit comments

Comments
 (0)