From f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427 Mon Sep 17 00:00:00 2001 From: Carlos Rodrigues Date: Thu, 15 Jul 2021 20:58:20 +0100 Subject: [PATCH] types(defineComponent): fix unwrap when returning `Ref|undefined` from `setup` (#4100) --- packages/reactivity/src/ref.ts | 6 +++++- test-dts/component.test-d.ts | 6 ++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/reactivity/src/ref.ts b/packages/reactivity/src/ref.ts index 0414ece2e5..3d1f1453ca 100644 --- a/packages/reactivity/src/ref.ts +++ b/packages/reactivity/src/ref.ts @@ -205,7 +205,11 @@ type BaseTypes = string | number | boolean export interface RefUnwrapBailTypes {} export type ShallowUnwrapRef = { - [K in keyof T]: T[K] extends Ref ? V : T[K] + [K in keyof T]: T[K] extends Ref + ? V + : T[K] extends Ref | undefined // if `V` is `unknown` that means it does not extend `Ref` and is undefined + ? unknown extends V ? undefined : V | undefined + : T[K] } export type UnwrapRef = T extends Ref diff --git a/test-dts/component.test-d.ts b/test-dts/component.test-d.ts index e679ffa6a4..93c3ea4109 100644 --- a/test-dts/component.test-d.ts +++ b/test-dts/component.test-d.ts @@ -159,6 +159,7 @@ describe('object props', () => { setupC: { a: ref(2) }, + setupD: undefined as Ref | undefined, setupProps: props } } @@ -190,7 +191,7 @@ describe('object props', () => { expectType(rawBindings.setupA) expectType>(rawBindings.setupB) expectType>(rawBindings.setupC.a) - expectType(rawBindings.setupA) + expectType | undefined>(rawBindings.setupD) // raw bindings props expectType(rawBindings.setupProps.a) @@ -215,7 +216,7 @@ describe('object props', () => { expectType(setup.setupA) expectType(setup.setupB) expectType>(setup.setupC.a) - expectType(setup.setupA) + expectType(setup.setupD) // raw bindings props expectType(setup.setupProps.a) @@ -239,6 +240,7 @@ describe('object props', () => { // instance const instance = new MyComponent() expectType(instance.setupA) + expectType(instance.setupD) // @ts-expect-error instance.notExist }) -- 2.47.3