From 9a571582b53220270e498d8712ea59312c0bef3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=B6=E8=BF=9C=E6=96=B9?= Date: Sat, 16 Dec 2023 13:45:01 +0800 Subject: [PATCH] fix(types): fix `shallowRef` type error (#9839) --- packages/dts-test/ref.test-d.ts | 18 +++++++++++++++--- packages/reactivity/src/ref.ts | 10 +++++++--- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/packages/dts-test/ref.test-d.ts b/packages/dts-test/ref.test-d.ts index a467c446d0a..f66ff926907 100644 --- a/packages/dts-test/ref.test-d.ts +++ b/packages/dts-test/ref.test-d.ts @@ -201,11 +201,23 @@ if (refStatus.value === 'initial') { expectType>(false) } -describe('shallowRef with generic', () => { - const r = ref({}) as MaybeRef - expectType | Ref>(shallowRef(r)) +describe('shallowRef with generic', () => { + const r = {} as T + const s = shallowRef(r) + expectType(s.value.name) + expectType>(shallowRef(r)) }) +{ + // should return ShallowRef | Ref, not ShallowRef> + expectType | Ref<{ name: string }>>( + shallowRef({} as MaybeRef<{ name: string }>) + ) + expectType | Ref | ShallowRef>( + shallowRef('' as Ref | string | number) + ) +} + // proxyRefs: should return `reactive` directly const r1 = reactive({ k: 'v' diff --git a/packages/reactivity/src/ref.ts b/packages/reactivity/src/ref.ts index f068844100e..a85c79c0bc6 100644 --- a/packages/reactivity/src/ref.ts +++ b/packages/reactivity/src/ref.ts @@ -114,9 +114,13 @@ export type ShallowRef = Ref & { [ShallowRefMarker]?: true } * @param value - The "inner value" for the shallow ref. * @see {@link https://vuejs.org/api/reactivity-advanced.html#shallowref} */ -export function shallowRef(value: MaybeRef): Ref | ShallowRef -export function shallowRef(value: T): T -export function shallowRef(value: T): ShallowRef +export function shallowRef( + value: T +): Ref extends T + ? T extends Ref + ? IfAny, T> + : ShallowRef + : ShallowRef export function shallowRef(): ShallowRef export function shallowRef(value?: unknown) { return createRef(value, true)