From b770232a69f3039af2ddf189261b9fc29e92a15c Mon Sep 17 00:00:00 2001 From: "marcin.piniarski" Date: Mon, 27 May 2024 15:17:47 +0200 Subject: [PATCH] feat: autofix in `define-props-declaration`: runtime syntax to type-based syntax (#2465) handle PropTypes (e.g. String as PropType<'test'>) --- lib/rules/define-props-declaration.js | 18 ++++ tests/lib/rules/define-props-declaration.js | 98 +++++++++++++++++++++ 2 files changed, 116 insertions(+) diff --git a/lib/rules/define-props-declaration.js b/lib/rules/define-props-declaration.js index 52c908ac2..fe55bfd43 100644 --- a/lib/rules/define-props-declaration.js +++ b/lib/rules/define-props-declaration.js @@ -61,6 +61,7 @@ module.exports = { }, /** @param {RuleContext} context */ create(context) { + const sourceCode = context.getSourceCode() /** * @param {Expression} node * @returns {string | null} @@ -76,6 +77,23 @@ module.exports = { if (typeProperty == null) { return null } + if (typeProperty.value.type === 'TSAsExpression') { + if ( + typeProperty.value.typeAnnotation.typeName.name !== 'PropType' + ) { + return null + } + + const typeArgument = + typeProperty.value.typeAnnotation.typeArguments.params[0] + if (typeArgument === undefined) { + return null + } + + const text = sourceCode.getText(typeArgument) + + return text + } return optionGetType(typeProperty.value) } case 'ArrayExpression': { diff --git a/tests/lib/rules/define-props-declaration.js b/tests/lib/rules/define-props-declaration.js index 9190496f4..b80ecdff8 100644 --- a/tests/lib/rules/define-props-declaration.js +++ b/tests/lib/rules/define-props-declaration.js @@ -288,6 +288,104 @@ tester.run('define-props-declaration', rule, { line: 3 } ] + }, + // Native Type with PropType + { + filename: 'test.vue', + code: ` + + `, + output: ` + + `, + errors: [ + { + message: 'Use type-based declaration instead of runtime declaration.', + line: 3 + } + ] + }, + // Object with PropType + { + filename: 'test.vue', + code: ` + + `, + output: ` + + `, + errors: [ + { + message: 'Use type-based declaration instead of runtime declaration.', + line: 3 + } + ] + }, + // Array with PropType + { + filename: 'test.vue', + code: ` + + `, + output: ` + + `, + errors: [ + { + message: 'Use type-based declaration instead of runtime declaration.', + line: 3 + } + ] + }, + // Function with PropType + { + filename: 'test.vue', + code: ` + + `, + output: ` + + `, + errors: [ + { + message: 'Use type-based declaration instead of runtime declaration.', + line: 3 + } + ] } ] })