import type * as babel from '@babel/core'; import type * as t from '@babel/types'; type TypeFilter = (node: t.Node) => node is V; export function isPathValid( path: unknown, key: TypeFilter, ): path is babel.NodePath { return key((path as babel.NodePath).node); } export type NestedExpression = | t.ParenthesizedExpression | t.TypeCastExpression | t.TSAsExpression | t.TSSatisfiesExpression | t.TSNonNullExpression | t.TSInstantiationExpression | t.TSTypeAssertion; export function isNestedExpression(node: t.Node): node is NestedExpression { switch (node.type) { case 'ParenthesizedExpression': case 'TypeCastExpression': case 'TSAsExpression': case 'TSSatisfiesExpression': case 'TSNonNullExpression': case 'TSTypeAssertion': case 'TSInstantiationExpression': return true; default: return false; } } type TypeCheck = K extends TypeFilter ? U : never; export function unwrapNode boolean>( node: t.Node, key: K, ): TypeCheck | undefined { if (key(node)) { return node as TypeCheck; } if (isNestedExpression(node)) { return unwrapNode(node.expression, key); } return undefined; } export function unwrapPath( path: unknown, key: TypeFilter, ): babel.NodePath | undefined { if (isPathValid(path, key)) { return path; } if (isPathValid(path, isNestedExpression)) { return unwrapPath(path.get('expression'), key); } return undefined; }