Skip to content

Commit

Permalink
chore: refactor fixTypeBased function
Browse files Browse the repository at this point in the history
  • Loading branch information
mpiniarski committed Jun 21, 2024
1 parent 100065d commit 7d9e731
Showing 1 changed file with 14 additions and 12 deletions.
26 changes: 14 additions & 12 deletions lib/rules/define-props-declaration.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,16 @@ function* fixTypeBased(fixer, node, props, context) {
const autoFixToSeparateInterface =
context.options[1]?.autoFixToSeparateInterface || false

const propTypes = props.map((prop) =>
const componentPropsData = props.map((prop) =>
getComponentPropData(prop, sourceCode)
)

const definePropsType = `{ ${propTypes
.map(
({ name, type, required, defaultValue }) =>
`${name}${required === false || defaultValue ? '?' : ''}: ${type}`
)
.join(PROPS_SEPARATOR)} }`
const componentPropsTypeCode = `{${componentPropsData
.map(({ name, type, required, defaultValue }) => {
const isOptional = required === false || defaultValue
return `${name}${isOptional ? '?' : ''}: ${type}`
})
.join(PROPS_SEPARATOR)}}`

// remove defineProps function parameters
yield fixer.replaceText(node.arguments[0], '')
Expand All @@ -43,17 +43,19 @@ function* fixTypeBased(fixer, node, props, context) {

yield fixer.insertTextBefore(
variableDeclarationNode,
`interface Props ${definePropsType.replace(/;/g, ',')}; `
`interface Props ${componentPropsTypeCode.replace(/;/g, ',')}; `
)
yield fixer.insertTextAfter(node.callee, `<Props>`)
} else {
yield fixer.insertTextAfter(node.callee, `<${definePropsType}>`)
yield fixer.insertTextAfter(node.callee, `<${componentPropsTypeCode}>`)
}

// add defaults if needed
const defaults = propTypes.filter(({ defaultValue }) => defaultValue)
if (defaults.length > 0) {
const defaultsCode = defaults
const propTypesDataWithDefaultValue = componentPropsData.filter(
({ defaultValue }) => defaultValue
)
if (propTypesDataWithDefaultValue.length > 0) {
const defaultsCode = propTypesDataWithDefaultValue
.map(
({ name, defaultValue }) =>
`${name}: ${sourceCode.getText(defaultValue)}`
Expand Down

0 comments on commit 7d9e731

Please sign in to comment.