Skip to content

Commit

Permalink
fix(types): ref value type unwrapping should happen at creation time
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Feb 26, 2020
1 parent 711d16c commit d4c6957
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 5 deletions.
4 changes: 2 additions & 2 deletions packages/reactivity/src/computed.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { effect, ReactiveEffect, trigger, track } from './effect'
import { TriggerOpTypes, TrackOpTypes } from './operations'
import { Ref, UnwrapRef } from './ref'
import { Ref } from './ref'
import { isFunction, NOOP } from '@vue/shared'

export interface ComputedRef<T = any> extends WritableComputedRef<T> {
readonly value: UnwrapRef<T>
readonly value: T
}

export interface WritableComputedRef<T> extends Ref<T> {
Expand Down
6 changes: 3 additions & 3 deletions packages/reactivity/src/ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export interface Ref<T = any> {
// don't want this internal field to leak into userland autocompletion -
// a private symbol, on the other hand, achieves just that.
[isRefSymbol]: true
value: UnwrapRef<T>
value: T
}

const convert = <T extends unknown>(val: T): T =>
Expand All @@ -28,13 +28,13 @@ export function isRef(r: any): r is Ref {
return r ? r._isRef === true : false
}

export function ref<T>(value: T): T extends Ref ? T : Ref<T>
export function ref<T>(value: T): T extends Ref ? T : Ref<UnwrapRef<T>>
export function ref<T = any>(): Ref<T>
export function ref(value?: unknown) {
return createRef(value)
}

export function shallowRef<T>(value: T): T extends Ref ? T : Ref<T>
export function shallowRef<T>(value: T): T extends Ref ? T : Ref<UnwrapRef<T>>
export function shallowRef<T = any>(): Ref<T>
export function shallowRef(value?: unknown) {
return createRef(value, true)
Expand Down
6 changes: 6 additions & 0 deletions test-dts/ref.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ function foo(arg: number | Ref<number>) {

// ref unwrapping
expectType<number>(unref(arg))

// ref inner type should be unwrapped
const nestedRef = ref({
foo: ref(1)
})
expectType<Ref<{ foo: number }>>(nestedRef)
}

foo(1)
10 changes: 10 additions & 0 deletions test-dts/watch.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,13 @@ watch(
},
{ immediate: true }
)

// should provide correct ref.value inner type to callbacks
const nestedRefSource = ref({
foo: ref(1)
})

watch(nestedRefSource, (v, ov) => {
expectType<{ foo: number }>(v)
expectType<{ foo: number }>(ov)
})

0 comments on commit d4c6957

Please sign in to comment.