Skip to content

Commit 1889468

Browse files
committed
feat(macros): improve handling of required props in defineComponent
1 parent e4d2357 commit 1889468

File tree

3 files changed

+23
-7
lines changed

3 files changed

+23
-7
lines changed

packages/macros/src/core/define-component/index.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import {
22
HELPER_PREFIX,
33
importHelperFn,
4+
walkAST,
45
walkIdentifiers,
56
type MagicStringAST,
67
} from '@vue-macros/common'
@@ -65,7 +66,15 @@ export function transformDefineComponent(
6566
continue
6667
}
6768
const defaultValue = getDefaultValue(prop.value.right)
68-
const isRequired = prop.value.right.type === 'TSNonNullExpression'
69+
let isRequired = false
70+
walkAST(prop.value.right, {
71+
enter(node) {
72+
if (node.type === 'TSNonNullExpression') {
73+
isRequired = true
74+
this.skip()
75+
}
76+
},
77+
})
6978

7079
const propOptions = []
7180
if (isRequired) {

packages/macros/src/volar/transform.ts

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,15 +67,22 @@ export function transformJsxMacros(
6767
? root.parameters[0].name.elements
6868
: []
6969
for (const element of elements) {
70-
if (ts.isIdentifier(element.name))
70+
if (ts.isIdentifier(element.name)) {
71+
const isRequired = ts.forEachChild(
72+
element,
73+
function isNonNullExpression(node): boolean {
74+
return (
75+
ts.isNonNullExpression(node) ||
76+
!!ts.forEachChild(node, isNonNullExpression)
77+
)
78+
},
79+
)
7180
props.push(
7281
`${element.name.escapedText}${
73-
element.initializer &&
74-
ts.isNonNullExpression(element.initializer)
75-
? ':'
76-
: '?:'
82+
isRequired ? ':' : '?:'
7783
} typeof ${element.name.escapedText}`,
7884
)
85+
}
7986
}
8087

8188
const shouldWrapByCall =

packages/macros/tests/fixtures/define-component.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { defineComponent, nextTick, unref } from 'vue'
33
const $ = unref
44

55
const Comp = defineComponent(
6-
({ bar = 'bar'!, Comp, ...attrs }: { bar: 'bar'; baz: 'baz', Comp: any }) => {
6+
({ bar = 'bar'! as string, Comp, ...attrs }: { bar: string; baz: 'baz', Comp: any }) => {
77
defineModel()
88
const foo = $(
99
defineModel('foo', {

0 commit comments

Comments
 (0)