Skip to content

Commit 099401e

Browse files
authored
fix(types/sfc): improve the type inference using withDefaults (#12872)
1 parent 67c1d26 commit 099401e

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

Diff for: types/test/setup-helpers-test.ts

+13-3
Original file line numberDiff line numberDiff line change
@@ -19,25 +19,35 @@ describe('defineProps w/ type declaration + withDefaults', () => {
1919
arr?: string[]
2020
obj?: { x: number }
2121
fn?: (e: string) => void
22-
x?: string
2322
genStr?: string
23+
x?: string
24+
y?: string
25+
z?: string
2426
}>(),
2527
{
2628
number: 123,
2729
arr: () => [],
2830
obj: () => ({ x: 123 }),
2931
fn: () => {},
30-
genStr: () => ''
32+
genStr: () => '',
33+
y: undefined,
34+
z: 'string'
3135
}
3236
)
3337

3438
res.number + 1
3539
res.arr.push('hi')
3640
res.obj.x
3741
res.fn('hi')
42+
res.genStr.slice()
3843
// @ts-expect-error
3944
res.x.slice()
40-
res.genStr.slice()
45+
// @ts-expect-error
46+
res.y.slice()
47+
48+
expectType<string | undefined>(res.x)
49+
expectType<string | undefined>(res.y)
50+
expectType<string>(res.z)
4151
})
4252

4353
describe('defineProps w/ union type declaration + withDefaults', () => {

Diff for: types/v3-setup-helpers.d.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,11 @@ type InferDefault<P, T> = T extends
110110
: (props: P) => T
111111

112112
type PropsWithDefaults<Base, Defaults> = Base & {
113-
[K in keyof Defaults]: K extends keyof Base ? NotUndefined<Base[K]> : never
113+
[K in keyof Defaults]: K extends keyof Base
114+
? Defaults[K] extends undefined
115+
? Base[K]
116+
: NotUndefined<Base[K]>
117+
: never
114118
}
115119

116120
/**

0 commit comments

Comments
 (0)