fix(compiler-sfc): add type for props's properties in prod mode (#4790)

fix #4783
This commit is contained in:
ygj6 2021-11-03 10:04:04 +08:00 committed by GitHub
parent d56f115f71
commit 090df0837e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 13 deletions

View File

@ -82,7 +82,9 @@ export default /*#__PURE__*/_defineComponent({
props: { props: {
foo: { default: 1 }, foo: { default: 1 },
bar: { default: () => {} }, bar: { default: () => {} },
baz: null baz: null,
boola: { type: Boolean },
boolb: { type: [Boolean, Number] }
}, },
setup(__props: any) { setup(__props: any) {

View File

@ -83,7 +83,7 @@ describe('sfc props transform', () => {
const { content } = compile( const { content } = compile(
` `
<script setup lang="ts"> <script setup lang="ts">
const { foo = 1, bar = {} } = defineProps<{ foo?: number, bar?: object, baz?: any }>() const { foo = 1, bar = {} } = defineProps<{ foo?: number, bar?: object, baz?: any, boola?: boolean, boolb?: boolean | number }>()
</script> </script>
`, `,
{ isProd: true } { isProd: true }
@ -93,7 +93,9 @@ describe('sfc props transform', () => {
expect(content).toMatch(`props: { expect(content).toMatch(`props: {
foo: { default: 1 }, foo: { default: 1 },
bar: { default: () => {} }, bar: { default: () => {} },
baz: null baz: null,
boola: { type: Boolean },
boolb: { type: [Boolean, Number] }
}`) }`)
assertCode(content) assertCode(content)
}) })

View File

@ -685,13 +685,20 @@ export function compileScript(
} }
} }
if (!isProd) {
const { type, required } = props[key] const { type, required } = props[key]
if (!isProd) {
return `${key}: { type: ${toRuntimeTypeString( return `${key}: { type: ${toRuntimeTypeString(
type type
)}, required: ${required}${ )}, required: ${required}${
defaultString ? `, ${defaultString}` : `` defaultString ? `, ${defaultString}` : ``
} }` } }`
} else if (type.indexOf('Boolean') > -1) {
// production: if boolean exists, should keep the type.
return `${key}: { type: ${toRuntimeTypeString(
type
)}${
defaultString ? `, ${defaultString}` : ``
} }`
} else { } else {
// production: checks are useless // production: checks are useless
return `${key}: ${defaultString ? `{ ${defaultString} }` : 'null'}` return `${key}: ${defaultString ? `{ ${defaultString} }` : 'null'}`
@ -1621,7 +1628,6 @@ function extractRuntimeProps(
m.key.type === 'Identifier' m.key.type === 'Identifier'
) { ) {
let type let type
if (!isProd) {
if (m.type === 'TSMethodSignature') { if (m.type === 'TSMethodSignature') {
type = ['Function'] type = ['Function']
} else if (m.typeAnnotation) { } else if (m.typeAnnotation) {
@ -1630,7 +1636,6 @@ function extractRuntimeProps(
declaredTypes declaredTypes
) )
} }
}
props[m.key.name] = { props[m.key.name] = {
key: m.key.name, key: m.key.name,
required: !m.optional, required: !m.optional,