Skip to content

fix(types/toRef): ensure compatibility for ShallowRef unions in TS <=5.3 #12996

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions packages/reactivity/src/ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -427,12 +429,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 }
? SafeShallowRef<T>
: T
: Ref<UnwrapRef<T>>
export function toRef<T extends object, K extends keyof T>(
object: T,
Expand Down