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 3941fa8
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
4 changes: 4 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
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 3941fa8

Please sign in to comment.