types(reactivity): add support for tuples in ref unwrapping (#436)

This commit is contained in:
Carlos Rodrigues 2019-11-08 17:52:24 +00:00 committed by Evan You
parent d7d87622ce
commit 68ad302714
2 changed files with 25 additions and 2 deletions

View File

@ -1,4 +1,4 @@
import { ref, effect, reactive, isRef, toRefs } from '../src/index'
import { ref, effect, reactive, isRef, toRefs, Ref } from '../src/index'
import { computed } from '@vue/runtime-dom'
describe('reactivity/ref', () => {
@ -107,6 +107,27 @@ describe('reactivity/ref', () => {
}
})
it('should keep tuple types', () => {
const tuple: [number, string, { a: number }, () => number, Ref<number>] = [
0,
'1',
{ a: 1 },
() => 0,
ref(0)
]
const tupleRef = ref(tuple)
tupleRef.value[0]++
expect(tupleRef.value[0]).toBe(1)
tupleRef.value[1] += '1'
expect(tupleRef.value[1]).toBe('11')
tupleRef.value[2].a++
expect(tupleRef.value[2].a).toBe(2)
expect(tupleRef.value[3]()).toBe(0)
tupleRef.value[4]++
expect(tupleRef.value[4]).toBe(1)
})
test('isRef', () => {
expect(isRef(ref(1))).toBe(true)
expect(isRef(computed(() => 1))).toBe(true)

View File

@ -72,11 +72,13 @@ function toProxyRef<T extends object, K extends keyof T>(
}
}
type UnwrapArray<T> = { [P in keyof T]: UnwrapRef<T[P]> }
// Recursively unwraps nested value bindings.
export type UnwrapRef<T> = {
cRef: T extends ComputedRef<infer V> ? UnwrapRef<V> : T
ref: T extends Ref<infer V> ? UnwrapRef<V> : T
array: T extends Array<infer V> ? Array<UnwrapRef<V>> : T
array: T extends Array<infer V> ? Array<UnwrapRef<V>> & UnwrapArray<T> : T
object: { [K in keyof T]: UnwrapRef<T[K]> }
}[T extends ComputedRef<any>
? 'cRef'