Skip to content
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

fix(types/ref): handle nested refs in UnwrapRef #12049

Merged
merged 2 commits into from
Sep 27, 2024
Merged
Show file tree
Hide file tree
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
18 changes: 18 additions & 0 deletions packages-private/dts-test/ref.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,24 @@ describe('allow getter and setter types to be unrelated', <T>() => {
f.value = ref(1)
})

describe('correctly unwraps nested refs', () => {
const obj = {
n: 24,
ref: ref(24),
nestedRef: ref({ n: ref(0) }),
}

const a = ref(obj)
expectType<number>(a.value.n)
expectType<number>(a.value.ref)
expectType<number>(a.value.nestedRef.n)

const b = reactive({ a })
expectType<number>(b.a.n)
expectType<number>(b.a.ref)
expectType<number>(b.a.nestedRef.n)
})

// computed
describe('allow computed getter and setter types to be unrelated', () => {
const obj = ref({
Expand Down
8 changes: 5 additions & 3 deletions packages/reactivity/src/ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ export function ref(value?: unknown) {

declare const ShallowRefMarker: unique symbol

export type ShallowRef<T = any> = Ref<T> & { [ShallowRefMarker]?: true }
export type ShallowRef<T = any, S = T> = Ref<T, S> & {
[ShallowRefMarker]?: true
}

/**
* Shallow version of {@link ref()}.
Expand Down Expand Up @@ -490,9 +492,9 @@ export type ShallowUnwrapRef<T> = {
type DistributeRef<T> = T extends Ref<infer V> ? V : T

export type UnwrapRef<T> =
T extends ShallowRef<infer V>
T extends ShallowRef<infer V, infer _>
? V
: T extends Ref<infer V>
: T extends Ref<infer V, infer _>
? UnwrapRefSimple<V>
: UnwrapRefSimple<T>

Expand Down