Skip to content

Commit

Permalink
feat: autofix in define-props-declaration: runtime syntax to type-b…
Browse files Browse the repository at this point in the history
…ased syntax (vuejs#2465)

handle separateInterface rule option
  • Loading branch information
mpiniarski committed May 27, 2024
1 parent f0294e8 commit 5a4a15e
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 5 deletions.
34 changes: 29 additions & 5 deletions lib/rules/define-props-declaration.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,15 @@ module.exports = {
schema: [
{
enum: ['type-based', 'runtime']
},
{
type: 'object',
properties: {
separateInterface: {
type: 'boolean',
default: false
}
}
}
],
messages: {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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, `<Props>`)
} else {
yield fixer.insertTextAfter(
node.callee,
`<${definePropsType}>`
)
}

const defaults = propTypes.filter(
({ defaultValue }) => defaultValue
)
Expand Down
25 changes: 25 additions & 0 deletions tests/lib/rules/define-props-declaration.js
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,31 @@ tester.run('define-props-declaration', rule, {
line: 3
}
]
},
// separate interface
{
filename: 'test.vue',
code: `
<script setup lang="ts">
const props = defineProps({
kind: {
type: Object as PropType<{ id: number; name: string }>
}
})
</script>
`,
output: `
<script setup lang="ts">
interface Props { kind: { id: number, name: string } }; const props = defineProps<Props>()
</script>
`,
options: ['type-based', { separateInterface: true }],
errors: [
{
message: 'Use type-based declaration instead of runtime declaration.',
line: 3
}
]
}
]
})

0 comments on commit 5a4a15e

Please sign in to comment.