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(reactivity): unwrapped refs typing (fix #9314) #9343

Closed
wants to merge 1 commit into from
Closed
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
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