Skip to content

Commit

Permalink
fix(types): fix ToRefs type on union value types
Browse files Browse the repository at this point in the history
fix #2687
  • Loading branch information
yyx990803 committed Dec 2, 2020
1 parent 24a7a2d commit e315d84
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
6 changes: 5 additions & 1 deletion packages/reactivity/src/ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ export interface Ref<T = any> {
}

export type ToRef<T> = T extends Ref ? T : Ref<UnwrapRef<T>>
export type ToRefs<T = any> = { [K in keyof T]: ToRef<T[K]> }
export type ToRefs<T = any> = {
// #2687: somehow using ToRef<T[K]> here turns the resulting type into
// a union of multiple Ref<*> types instead of a single Ref<* | *> type.
[K in keyof T]: T[K] extends Ref ? T[K] : Ref<UnwrapRef<T[K]>>
}

const convert = <T extends unknown>(val: T): T =>
isObject(val) ? reactive(val) : val
Expand Down
27 changes: 25 additions & 2 deletions test-dts/ref.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import {
expectType,
proxyRefs,
toRef,
toRefs
toRefs,
ToRefs
} from './index'

function plainType(arg: number | Ref<number>) {
Expand All @@ -28,7 +29,6 @@ function plainType(arg: number | Ref<number>) {
const nestedRef = ref({
foo: ref(1)
})
expectType<Ref<{ foo: number }>>(nestedRef)
expectType<{ foo: number }>(nestedRef.value)

// ref boolean
Expand Down Expand Up @@ -171,3 +171,26 @@ expectType<{
a: Ref<number>
b: Ref<number>
}>(objRefs)

// #2687
interface AppData {
state: 'state1' | 'state2' | 'state3'
}

const data: ToRefs<AppData> = toRefs(
reactive({
state: 'state1'
})
)

switch (data.state.value) {
case 'state1':
data.state.value = 'state2'
break
case 'state2':
data.state.value = 'state3'
break
case 'state3':
data.state.value = 'state1'
break
}

0 comments on commit e315d84

Please sign in to comment.