From db1153d756980fa0f0b2dd1427b84acc8740dd69 Mon Sep 17 00:00:00 2001 From: tycho <jh.leong@outlook.com> Date: Wed, 5 Mar 2025 13:58:03 +0800 Subject: [PATCH 1/2] fix(types/toRef): ensure compatibility for `ShallowRef` unions in TS <=5.3 --- packages/reactivity/src/ref.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/reactivity/src/ref.ts b/packages/reactivity/src/ref.ts index 6b8d541819d..86a8571805c 100644 --- a/packages/reactivity/src/ref.ts +++ b/packages/reactivity/src/ref.ts @@ -427,12 +427,15 @@ export type ToRef<T> = IfAny<T, Ref<T>, [T] extends [Ref] ? T : Ref<T>> * @param [key] - (optional) Name of the property in the reactive object. * @see {@link https://vuejs.org/api/reactivity-utilities.html#toref} */ -export function toRef<T>( - value: T, -): T extends () => infer R +export function toRef<T>(value: T): T extends () => infer R ? Readonly<Ref<R>> : T extends Ref - ? T + ? // #12986 Workaround for TS <=5.3: Avoids type errors when T is a union + // containing `ShallowRef`, without raising the minimum TS version + // requirement. + T extends { [ShallowRefMarker]?: true } + ? T | ShallowRef<never> + : T : Ref<UnwrapRef<T>> export function toRef<T extends object, K extends keyof T>( object: T, From 122f05a0f68e06d3fa7e1c6edd3e9dc523dafe0e Mon Sep 17 00:00:00 2001 From: tycho <jh.leong@outlook.com> Date: Wed, 5 Mar 2025 14:40:38 +0800 Subject: [PATCH 2/2] refactor: improve type readability --- packages/reactivity/src/ref.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/reactivity/src/ref.ts b/packages/reactivity/src/ref.ts index 86a8571805c..1be1c4de571 100644 --- a/packages/reactivity/src/ref.ts +++ b/packages/reactivity/src/ref.ts @@ -384,6 +384,8 @@ class GetterRefImpl<T> { export type ToRef<T> = IfAny<T, Ref<T>, [T] extends [Ref] ? T : Ref<T>> +type SafeShallowRef<T> = T | ShallowRef<never> + /** * Used to normalize values / refs / getters into refs. * @@ -434,7 +436,7 @@ export function toRef<T>(value: T): T extends () => infer R // containing `ShallowRef`, without raising the minimum TS version // requirement. T extends { [ShallowRefMarker]?: true } - ? T | ShallowRef<never> + ? SafeShallowRef<T> : T : Ref<UnwrapRef<T>> export function toRef<T extends object, K extends keyof T>(