Estoy usando JSCodeshift para migrar algunos archivos JS antiguos. Una de las cosas que tengo que hacer es encontrar todas las funciones (tanto las funciones normales como las de flecha) y luego agregar algo de código a su cuerpo. Para encontrar ambos, solo uso el constructor general de funciones para buscar todas las funciones posibles. Sin embargo, cuando trato de usar los nodos de búsqueda en la función jscodeshift, aparece un error de tipo. Entonces, este código simple puede funcionar como un ejemplo:
j(file.source).find(j.Function).filter((path) => { j(path) // <- here is where the error happens })
Este es el error completo:
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)
Mirando la definición de Error, está extendiendo ASTNode, por lo que debería ser compatible, ¿no?
//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; }
Sin embargo, si uso ArrowFunctionExpression como consulta de búsqueda:
j(file.source).find(j.ArrowFunctionExpression).filter((path) => { j(path) })
no se queja del tipo, lo cual es extraño dado que ArrowFunctionExpression solo extiende el tipo de función
interface ArrowFunctionExpression extends Omit<Function, "type" | "id" | "body" | "generator">, Omit<Expression, "type"> { type: "ArrowFunctionExpression"; id?: null; body: K.BlockStatementKind | K.ExpressionKind; generator?: false; }