Skip to content

Commit

Permalink
fix(compiler-sfc): ensure use union type with undefined to define pro…
Browse files Browse the repository at this point in the history
…ps will transform to {required: false}
  • Loading branch information
linshuohao committed Aug 23, 2022
1 parent 81a7819 commit b778626
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
Expand Up @@ -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 },
Expand Down
5 changes: 5 additions & 0 deletions packages/compiler-sfc/__tests__/compileScript.spec.ts
Expand Up @@ -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
Expand Down Expand Up @@ -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 }`
Expand Down Expand Up @@ -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,
Expand Down
12 changes: 11 additions & 1 deletion packages/compiler-sfc/src/compileScript.ts
Expand Up @@ -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`]
}
}
Expand Down Expand Up @@ -1847,6 +1854,9 @@ function inferRuntimeType(
case 'TSSymbolKeyword':
return ['Symbol']

case 'TSUndefinedKeyword':
return ['undefined']

default:
return [`null`] // no runtime check
}
Expand Down

0 comments on commit b778626

Please sign in to comment.