diff --git a/packages/compiler-sfc/__tests__/compileScript.spec.ts b/packages/compiler-sfc/__tests__/compileScript.spec.ts index 08d404b9c16..068a050ca73 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 }` 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 }