From 168c8572475c82902f9cb0480f85b5d3100ffa0d Mon Sep 17 00:00:00 2001 From: littleboarx <59130959+littleboarx@users.noreply.github.com> Date: Tue, 8 Nov 2022 10:59:31 +0800 Subject: [PATCH] fix(sfc/types): improve the type inference using withDefaults (#6764) fix #6552 --- packages/runtime-core/src/apiSetupHelpers.ts | 6 +++++- test-dts/setupHelpers.test-d.ts | 16 +++++++++++++--- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/packages/runtime-core/src/apiSetupHelpers.ts b/packages/runtime-core/src/apiSetupHelpers.ts index a8b7fcdef31..0ab3d252d55 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 6b9c67b2897..d099d37441d 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', () => {