Skip to content

Commit

Permalink
fix(types/ref): handle nested refs in UnwrapRef
Browse files Browse the repository at this point in the history
  • Loading branch information
jh-leong committed Sep 27, 2024
1 parent a77b959 commit 31c7e9b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
17 changes: 17 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,23 @@ describe('allow getter and setter types to be unrelated', <T>() => {
f.value = ref(1)
})

describe('correctly unwraps nested ref', () => {
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)
})

// 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 31c7e9b

Please sign in to comment.