Skip to content

Commit

Permalink
fix(reactivity): unwrapped refs typing (fix #9314)
Browse files Browse the repository at this point in the history
  • Loading branch information
Othmane BENTALEB committed Oct 13, 2023
1 parent b8fc18c commit 8913e48
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
21 changes: 21 additions & 0 deletions packages/dts-test/ref.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -388,3 +388,24 @@ describe('toRef <-> toValue', () => {
)
)
})

// #9314
describe('Ref Unwrapping', () => {
const num = ref(0)
expectType<Ref<number>>(num)

const obj1 = ref({ count: ref(0) })
const obj2 = reactive({ count: ref(0) })
expectType<number>(obj1.value.count)
expectType<number>(obj2.count)

const map1 = ref(new Map([['count', ref(0)]]))
const map2 = reactive(new Map([['count', ref(0)]]))
expectType<Ref<number>>(map1.value.get('count')!)
expectType<Ref<number>>(map2.get('count')!)

const map3 = ref(new Map([['count', { foo: ref(0) }]]))
const map4 = reactive(new Map([['count', { foo: ref(0) }]]))
expectType<{ foo: number }>(map3.value.get('count')!)
expectType<{ foo: number }>(map4.get('count')!)
})
13 changes: 12 additions & 1 deletion packages/reactivity/src/ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -490,14 +490,25 @@ export type UnwrapRef<T> = T extends ShallowRef<infer V>
? UnwrapRefSimple<V>
: UnwrapRefSimple<T>

type UnwrapRefCollection<T extends CollectionTypes> = T extends Set<infer V>
? Set<UnwrapRefSimple<V>>
: T extends Map<infer K, infer V>
? Map<K, UnwrapRefSimple<V>>
: T extends WeakSet<infer V>
? WeakSet<UnwrapRefSimple<V>>
: T extends WeakMap<infer K, infer V>
? WeakMap<K, UnwrapRefSimple<V>>
: T

export type UnwrapRefSimple<T> = T extends
| Function
| CollectionTypes
| BaseTypes
| Ref
| RefUnwrapBailTypes[keyof RefUnwrapBailTypes]
| { [RawSymbol]?: true }
? T
: T extends CollectionTypes
? UnwrapRefCollection<T>
: T extends ReadonlyArray<any>
? { [K in keyof T]: UnwrapRefSimple<T[K]> }
: T extends object & { [ShallowReactiveMarker]?: never }
Expand Down

0 comments on commit 8913e48

Please sign in to comment.