Skip to content

Commit

Permalink
fix(types/ref): handle nested refs in UnwrapRef (#12049)
Browse files Browse the repository at this point in the history
close #12044
  • Loading branch information
jh-leong authored Sep 27, 2024
1 parent ea3efa0 commit e2c19c2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
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

0 comments on commit e2c19c2

Please sign in to comment.