diff --git a/packages/compiler-sfc/__tests__/__snapshots__/compileScript.spec.ts.snap b/packages/compiler-sfc/__tests__/__snapshots__/compileScript.spec.ts.snap index b7fc9304b26..872a382982c 100644 --- a/packages/compiler-sfc/__tests__/__snapshots__/compileScript.spec.ts.snap +++ b/packages/compiler-sfc/__tests__/__snapshots__/compileScript.spec.ts.snap @@ -1522,6 +1522,7 @@ export default /*#__PURE__*/_defineComponent({ method: { type: Function, required: true }, symbol: { type: Symbol, required: true }, union: { type: [String, Number], required: true }, + unionWithUndefined: { type: Number, required: false }, literalUnion: { type: String, required: true }, literalUnionNumber: { type: Number, required: true }, literalUnionMixed: { type: [String, Number, Boolean], required: true }, diff --git a/packages/compiler-sfc/__tests__/compileScript.spec.ts b/packages/compiler-sfc/__tests__/compileScript.spec.ts index 08d404b9c16..1747197fa26 100644 --- a/packages/compiler-sfc/__tests__/compileScript.spec.ts +++ b/packages/compiler-sfc/__tests__/compileScript.spec.ts @@ -801,6 +801,7 @@ const emit = defineEmits(['a', 'b']) symbol: symbol union: string | number + unionWithUndefined: number | undefined literalUnion: 'foo' | 'bar' literalUnionNumber: 1 | 2 | 3 | 4 | 5 literalUnionMixed: 'foo' | 1 | boolean @@ -832,6 +833,9 @@ const emit = defineEmits(['a', 'b']) expect(content).toMatch( `union: { type: [String, Number], required: true }` ) + expect(content).toMatch( + `unionWithUndefined: { type: Number, required: false }` + ) expect(content).toMatch(`literalUnion: { type: String, required: true }`) expect(content).toMatch( `literalUnionNumber: { type: Number, required: true }` @@ -863,6 +867,7 @@ const emit = defineEmits(['a', 'b']) method: BindingTypes.PROPS, symbol: BindingTypes.PROPS, union: BindingTypes.PROPS, + unionWithUndefined: BindingTypes.PROPS, literalUnion: BindingTypes.PROPS, literalUnionNumber: BindingTypes.PROPS, literalUnionMixed: BindingTypes.PROPS, diff --git a/packages/compiler-sfc/src/compileScript.ts b/packages/compiler-sfc/src/compileScript.ts index 5a77e8a9463..6d8ea54d6dc 100644 --- a/packages/compiler-sfc/src/compileScript.ts +++ b/packages/compiler-sfc/src/compileScript.ts @@ -1756,9 +1756,16 @@ function extractRuntimeProps( } else if (m.typeAnnotation) { type = inferRuntimeType(m.typeAnnotation.typeAnnotation, declaredTypes) } + + let undefinedIdx = type?.indexOf('undefined') ?? -1 + + if (undefinedIdx > -1) { + type?.splice(undefinedIdx, 1) + } + props[m.key.name] = { key: m.key.name, - required: !m.optional, + required: !m.optional && undefinedIdx === -1, type: type || [`null`] } } @@ -1847,6 +1854,9 @@ function inferRuntimeType( case 'TSSymbolKeyword': return ['Symbol'] + case 'TSUndefinedKeyword': + return ['undefined'] + default: return [`null`] // no runtime check }