From 5a4a15e2d57dfc0c29f746cd6fc1ddea99eb27df Mon Sep 17 00:00:00 2001 From: "marcin.piniarski" Date: Mon, 27 May 2024 16:01:47 +0200 Subject: [PATCH] feat: autofix in `define-props-declaration`: runtime syntax to type-based syntax (#2465) handle separateInterface rule option --- lib/rules/define-props-declaration.js | 34 ++++++++++++++++++--- tests/lib/rules/define-props-declaration.js | 25 +++++++++++++++ 2 files changed, 54 insertions(+), 5 deletions(-) diff --git a/lib/rules/define-props-declaration.js b/lib/rules/define-props-declaration.js index f4f145c91..f05e6da3c 100644 --- a/lib/rules/define-props-declaration.js +++ b/lib/rules/define-props-declaration.js @@ -52,6 +52,15 @@ module.exports = { schema: [ { enum: ['type-based', 'runtime'] + }, + { + type: 'object', + properties: { + separateInterface: { + type: 'boolean', + default: false + } + } } ], messages: { @@ -156,6 +165,8 @@ module.exports = { } const defineType = context.options[0] || 'type-based' + const separateInterface = context.options[1]?.separateInterface || false + return utils.defineScriptSetupVisitor(context, { onDefinePropsEnter(node, props) { switch (defineType) { @@ -194,15 +205,28 @@ module.exports = { const definePropsType = `{ ${propTypes .map( ({ name, type, required, defaultValue }) => - `${name}${(required === false || defaultValue) ? '?' : ''}: ${type}` + `${name}${required === false || defaultValue ? '?' : ''}: ${type}` ) .join(', ')} }` yield fixer.replaceText(node.arguments[0], '') - yield fixer.insertTextAfter( - node.callee, - `<${definePropsType}>` - ) + + if (separateInterface) { + const variableDeclarationNode = node.parent.parent + if (!variableDeclarationNode) return + + yield fixer.insertTextBefore( + variableDeclarationNode, + `interface Props ${definePropsType.replaceAll(';', ',')}; ` + ) + yield fixer.insertTextAfter(node.callee, ``) + } else { + yield fixer.insertTextAfter( + node.callee, + `<${definePropsType}>` + ) + } + const defaults = propTypes.filter( ({ defaultValue }) => defaultValue ) diff --git a/tests/lib/rules/define-props-declaration.js b/tests/lib/rules/define-props-declaration.js index 3c7cf0785..6f4925480 100644 --- a/tests/lib/rules/define-props-declaration.js +++ b/tests/lib/rules/define-props-declaration.js @@ -460,6 +460,31 @@ tester.run('define-props-declaration', rule, { line: 3 } ] + }, + // separate interface + { + filename: 'test.vue', + code: ` + + `, + output: ` + + `, + options: ['type-based', { separateInterface: true }], + errors: [ + { + message: 'Use type-based declaration instead of runtime declaration.', + line: 3 + } + ] } ] })