Skip to content

Commit

Permalink
refactor(compiler-sfc): drop Function prop type when no static defaul…
Browse files Browse the repository at this point in the history
…t value (#7125)
  • Loading branch information
sxzz committed Nov 14, 2022
1 parent 0187f99 commit 4e5d9cd
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 2 deletions.
Expand Up @@ -1784,6 +1784,29 @@ const props = __props as { foo: string, bar?: number, baz: boolean, qux(): numbe



return { props }
}

})"
`;

exports[`SFC compile <script setup> with TypeScript withDefaults (static) w/ production mode 1`] = `
"import { defineComponent as _defineComponent } from 'vue'

export default /*#__PURE__*/_defineComponent({
props: {
foo: null,
bar: { type: Boolean },
baz: { type: [Boolean, Function], default: true },
qux: { default: 'hi' }
},
setup(__props: any, { expose }) {
expose();

const props = __props as { foo: () => void, bar: boolean, baz: boolean | (() => void), qux: string | number };



return { props }
}

Expand Down
30 changes: 30 additions & 0 deletions packages/compiler-sfc/__tests__/compileScript.spec.ts
Expand Up @@ -1121,6 +1121,36 @@ const emit = defineEmits(['a', 'b'])
})
})

// #7111
test('withDefaults (static) w/ production mode', () => {
const { content } = compile(
`
<script setup lang="ts">
const props = withDefaults(defineProps<{
foo: () => void
bar: boolean
baz: boolean | (() => void)
qux: string | number
}>(), {
baz: true,
qux: 'hi'
})
</script>
`,
{ isProd: true }
)
assertCode(content)
expect(content).toMatch(`const props = __props`)

// foo has no default value, the Function can be dropped
expect(content).toMatch(`foo: null`)
expect(content).toMatch(`bar: { type: Boolean }`)
expect(content).toMatch(
`baz: { type: [Boolean, Function], default: true }`
)
expect(content).toMatch(`qux: { default: 'hi' }`)
})

test('withDefaults (dynamic)', () => {
const { content } = compile(`
<script setup lang="ts">
Expand Down
11 changes: 9 additions & 2 deletions packages/compiler-sfc/src/compileScript.ts
Expand Up @@ -822,8 +822,15 @@ export function compileScript(
)}, required: ${required}${
defaultString ? `, ${defaultString}` : ``
} }`
} else if (type.some(el => el === 'Boolean' || el === 'Function')) {
// #4783, #7111 for boolean or function, should keep the type
} else if (
type.some(
el =>
el === 'Boolean' ||
((!hasStaticDefaults || defaultString) && el === 'Function')
)
) {
// #4783 for boolean, should keep the type
// #7111 for function, if default value exists or it's not static, should keep it
// in production
return `${key}: { type: ${toRuntimeTypeString(type)}${
defaultString ? `, ${defaultString}` : ``
Expand Down

0 comments on commit 4e5d9cd

Please sign in to comment.