Skip to content

Commit 04e5835

Browse files
fix(types/sfc): fix withDefaults type inference when using union types (#4925)
1 parent fa2237f commit 04e5835

File tree

2 files changed

+28
-12
lines changed

2 files changed

+28
-12
lines changed

packages/runtime-core/src/apiSetupHelpers.ts

+13-12
Original file line numberDiff line numberDiff line change
@@ -127,20 +127,21 @@ export function defineExpose(exposed?: Record<string, any>) {
127127
type NotUndefined<T> = T extends undefined ? never : T
128128

129129
type InferDefaults<T> = {
130-
[K in keyof T]?: NotUndefined<T[K]> extends
131-
| number
132-
| string
133-
| boolean
134-
| symbol
135-
| Function
136-
? NotUndefined<T[K]>
137-
: (props: T) => NotUndefined<T[K]>
130+
[K in keyof T]?: InferDefault<T, NotUndefined<T[K]>>
138131
}
139132

140-
type PropsWithDefaults<Base, Defaults> = Base &
141-
{
142-
[K in keyof Defaults]: K extends keyof Base ? NotUndefined<Base[K]> : never
143-
}
133+
type InferDefault<P, T> = T extends
134+
| number
135+
| string
136+
| boolean
137+
| symbol
138+
| Function
139+
? T
140+
: (props: P) => T
141+
142+
type PropsWithDefaults<Base, Defaults> = Base & {
143+
[K in keyof Defaults]: K extends keyof Base ? NotUndefined<Base[K]> : never
144+
}
144145

145146
/**
146147
* Vue `<script setup>` compiler macro for providing props default values when

test-dts/setupHelpers.test-d.ts

+15
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,21 @@ describe('defineProps w/ type declaration + withDefaults', () => {
4545
res.x.slice()
4646
})
4747

48+
describe('defineProps w/ union type declaration + withDefaults', () => {
49+
withDefaults(
50+
defineProps<{
51+
union1?: number | number[] | { x: number }
52+
union2?: number | number[] | { x: number }
53+
union3?: number | number[] | { x: number }
54+
}>(),
55+
{
56+
union1: 123,
57+
union2: () => [123],
58+
union3: () => ({ x: 123 })
59+
}
60+
)
61+
})
62+
4863
describe('defineProps w/ runtime declaration', () => {
4964
// runtime declaration
5065
const props = defineProps({

0 commit comments

Comments
 (0)