From: littleboarx <59130959+littleboarx@users.noreply.github.com> Date: Tue, 8 Nov 2022 02:59:31 +0000 (+0800) Subject: fix(sfc/types): improve the type inference using withDefaults (#6764) X-Git-Tag: v3.2.42~31 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=168c8572475c82902f9cb0480f85b5d3100ffa0d;p=thirdparty%2Fvuejs%2Fcore.git fix(sfc/types): improve the type inference using withDefaults (#6764) fix #6552 --- diff --git a/packages/runtime-core/src/apiSetupHelpers.ts b/packages/runtime-core/src/apiSetupHelpers.ts index a8b7fcdef3..0ab3d252d5 100644 --- a/packages/runtime-core/src/apiSetupHelpers.ts +++ b/packages/runtime-core/src/apiSetupHelpers.ts @@ -143,7 +143,11 @@ type InferDefault = T extends : (props: P) => T type PropsWithDefaults = Base & { - [K in keyof Defaults]: K extends keyof Base ? NotUndefined : never + [K in keyof Defaults]: K extends keyof Base + ? Defaults[K] extends undefined + ? Base[K] + : NotUndefined + : never } /** diff --git a/test-dts/setupHelpers.test-d.ts b/test-dts/setupHelpers.test-d.ts index 6b9c67b289..d099d37441 100644 --- a/test-dts/setupHelpers.test-d.ts +++ b/test-dts/setupHelpers.test-d.ts @@ -27,15 +27,19 @@ describe('defineProps w/ type declaration + withDefaults', () => { arr?: string[] obj?: { x: number } fn?: (e: string) => void - x?: string genStr?: string + x?: string + y?: string + z?: string }>(), { number: 123, arr: () => [], obj: () => ({ x: 123 }), fn: () => {}, - genStr: () => '' + genStr: () => '', + y: undefined, + z: 'string' } ) @@ -43,9 +47,15 @@ describe('defineProps w/ type declaration + withDefaults', () => { res.arr.push('hi') res.obj.x res.fn('hi') + res.genStr.slice() // @ts-expect-error res.x.slice() - res.genStr.slice() + // @ts-expect-error + res.y.slice() + + expectType(res.x) + expectType(res.y) + expectType(res.z) }) describe('defineProps w/ union type declaration + withDefaults', () => {