我正在使用 JSCodeshift 迁移一些旧的 JS 文件。我要做的一件事是找到所有函数(普通函数和箭头函数),然后在它们的主体中添加一些代码。要找到两者,我只需使用通用 Function 构造函数来搜索所有可能的函数。但是,当我尝试在 jscodeshift 函数上使用 find 节点时,会出现类型错误。所以,这个简单的代码可以作为一个例子:
j(file.source).find(j.Function).filter((path) => {
j(path) // <- here is where the error happens
})
这是完整的错误:
Overload 2 of 2, '(source: ASTNode | ASTNode[] | ASTPath<ASTNode> | ASTPath<ASTNode>[]): Collection<any>', gave the following error.
Argument of type 'ASTPath<Function>' is not assignable to parameter of type 'ASTNode | ASTNode[] | ASTPath<ASTNode> | ASTPath<ASTNode>[]'.
Type 'NodePath<Function, Function>' is not assignable to type 'ASTPath<ASTNode>'.
Type 'Function' is not assignable to type 'ASTNode'.
Property 'key' is missing in type 'Function' but required in type 'ClassPrivateMethod'.ts(2769)
看Error的定义,是扩展ASTNode,应该兼容吧?
//ast-types/gen/namedTypes.d.ts
interface Function extends Node {
id?: K.IdentifierKind | null;
params: K.PatternKind[];
body: K.BlockStatementKind;
generator?: boolean;
async?: boolean;
expression?: boolean;
defaults?: (K.ExpressionKind | null)[];
rest?: K.IdentifierKind | null;
returnType?: K.TypeAnnotationKind | K.TSTypeAnnotationKind | null;
typeParameters?: K.TypeParameterDeclarationKind | K.TSTypeParameterDeclarationKind | null;
predicate?: K.FlowPredicateKind | null;
}
但是,如果我使用 ArrowFunctionExpression 作为查找查询:
j(file.source).find(j.ArrowFunctionExpression).filter((path) => {
j(path)
})
它不会抱怨类型,这很奇怪,因为 ArrowFunctionExpression 只是扩展了 Function 类型
interface ArrowFunctionExpression extends Omit<Function, "type" | "id" | "body" | "generator">, Omit<Expression, "type"> {
type: "ArrowFunctionExpression";
id?: null;
body: K.BlockStatementKind | K.ExpressionKind;
generator?: false;
}