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

Improve the type definition of path.isX #15661

Merged
merged 4 commits into from Jul 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 8 additions & 1 deletion packages/babel-traverse/scripts/generators/asserts.js
Expand Up @@ -8,13 +8,20 @@ export default function generateAsserts() {
import type * as t from "@babel/types";
import type NodePath from "../index";

type Opts<Obj> = Partial<{
[Prop in keyof Obj]: Obj[Prop] extends t.Node
? t.Node
: Obj[Prop] extends t.Node[]
? t.Node[]
: Obj[Prop];
}>;

export interface NodePathAssertions {`;

for (const type of [...t.TYPES].sort()) {
output += `
assert${type}(
opts?: object,
opts?: Opts<t.${type}>,
): asserts this is NodePath<t.${type}>;`;
}

Expand Down
13 changes: 11 additions & 2 deletions packages/babel-traverse/scripts/generators/validators.js
Expand Up @@ -9,18 +9,27 @@ import type * as t from "@babel/types";
import type NodePath from "../index";
import type { VirtualTypeNodePathValidators } from "../lib/virtual-types-validator";

type Opts<Obj> = Partial<{
[Prop in keyof Obj]: Obj[Prop] extends t.Node
? t.Node
: Obj[Prop] extends t.Node[]
? t.Node[]
: Obj[Prop];
}>;

interface BaseNodePathValidators {
`;

for (const type of [...t.TYPES].sort()) {
output += `is${type}<T extends t.Node>(this: NodePath<T>, opts?: object): this is NodePath<T & t.${type}>;`;
output += `is${type}<T extends t.Node>(this: NodePath<T>, opts?: Opts<t.${type}>): this is NodePath<T & t.${type}>;`;
}

output += `
}

export interface NodePathValidators
extends BaseNodePathValidators, VirtualTypeNodePathValidators {}
extends Omit<BaseNodePathValidators, keyof VirtualTypeNodePathValidators>,
VirtualTypeNodePathValidators {}
`;

return output;
Expand Down