能否通过代码片段将函数参数转换为解构对象形式?
实现函数参数到解构对象的快速转换
当然可以实现,下面提供两种实用方案:
一、编辑器代码片段一键转换(以VS Code为例)
直接在VS Code里自定义代码片段,选中参数后就能快速替换:
- 打开用户代码片段面板:按
Ctrl+Shift+P,搜索并选择"Configure User Snippets",再选择对应的javascript.json或typescript.json文件。 - 添加以下代码片段:
{ "转解构对象参数": { "prefix": "destruct", "body": [ "{ ${TM_SELECTED_TEXT/((\\w+):\\s*\\w+)(,\\s*)?/${1}/g} }: { ${TM_SELECTED_TEXT/((\\w+):\\s*\\w+)(,\\s*)?/${1};/g} }" ], "description": "把普通函数参数转为带类型的解构对象" } }
- 使用方式:选中函数的参数列表(比如
arg1: string, arg2: string),输入前缀destruct后按回车,就能直接转换成目标格式。
二、AST工具程序化转换
如果需要批量处理代码,用AST解析工具可以自动完成转换:
- 先安装依赖:
npm install recast @babel/parser @babel/types
- 编写转换脚本:
const recast = require('recast'); const babelParser = require('@babel/parser'); const t = require('@babel/types'); const sourceCode = `const before = (arg1: string, arg2: string) => null;`; // 解析代码生成AST const ast = recast.parse(sourceCode, { parser: { parse: code => babelParser.parse(code, { sourceType: 'module', plugins: ['typescript'] }) } }); // 遍历AST转换参数结构 recast.visit(ast, { visitArrowFunctionExpression(path) { const params = path.node.params; // 判断是否是需要转换的普通带类型参数 if (params.length > 0 && params.every(p => t.isIdentifier(p) && p.typeAnnotation)) { // 构建对象类型属性 const typeProps = params.map(p => t.objectTypeProperty(t.identifier(p.name), p.typeAnnotation.typeAnnotation) ); // 构建解构模式 const destructPattern = t.objectPattern( params.map(p => t.objectProperty(t.identifier(p.name), t.identifier(p.name))) ); // 添加类型注解 destructPattern.typeAnnotation = t.typeAnnotation(t.objectTypeAnnotation(typeProps)); // 替换原参数 path.node.params = [destructPattern]; } return false; } }); // 输出转换后的代码 console.log(recast.print(ast).code);
运行脚本后就能得到你需要的转换结果。
内容的提问来源于stack exchange,提问作者Thibaud Rouchon
相关产品推荐
相关产品推荐

