Skip to content

Commit 168c857

Browse files
authoredNov 8, 2022
fix(sfc/types): improve the type inference using withDefaults (#6764)
fix #6552
1 parent 79e7c1e commit 168c857

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed
 

‎packages/runtime-core/src/apiSetupHelpers.ts

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

145145
type PropsWithDefaults<Base, Defaults> = Base & {
146-
[K in keyof Defaults]: K extends keyof Base ? NotUndefined<Base[K]> : never
146+
[K in keyof Defaults]: K extends keyof Base
147+
? Defaults[K] extends undefined
148+
? Base[K]
149+
: NotUndefined<Base[K]>
150+
: never
147151
}
148152

149153
/**

‎test-dts/setupHelpers.test-d.ts

+13-3
Original file line numberDiff line numberDiff line change
@@ -27,25 +27,35 @@ describe('defineProps w/ type declaration + withDefaults', () => {
2727
arr?: string[]
2828
obj?: { x: number }
2929
fn?: (e: string) => void
30-
x?: string
3130
genStr?: string
31+
x?: string
32+
y?: string
33+
z?: string
3234
}>(),
3335
{
3436
number: 123,
3537
arr: () => [],
3638
obj: () => ({ x: 123 }),
3739
fn: () => {},
38-
genStr: () => ''
40+
genStr: () => '',
41+
y: undefined,
42+
z: 'string'
3943
}
4044
)
4145

4246
res.number + 1
4347
res.arr.push('hi')
4448
res.obj.x
4549
res.fn('hi')
50+
res.genStr.slice()
4651
// @ts-expect-error
4752
res.x.slice()
48-
res.genStr.slice()
53+
// @ts-expect-error
54+
res.y.slice()
55+
56+
expectType<string | undefined>(res.x)
57+
expectType<string | undefined>(res.y)
58+
expectType<string>(res.z)
4959
})
5060

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

0 commit comments

Comments
 (0)
Please sign in to comment.