reactivity.test-d.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import { ref, readonly, shallowReadonly, Ref, reactive, markRaw } from 'vue'
  2. import { describe, expectType } from './utils'
  3. describe('should support DeepReadonly', () => {
  4. const r = readonly({ obj: { k: 'v' } })
  5. // @ts-expect-error
  6. r.obj = {}
  7. // @ts-expect-error
  8. r.obj.k = 'x'
  9. })
  10. // #4180
  11. describe('readonly ref', () => {
  12. const r = readonly(ref({ count: 1 }))
  13. expectType<Ref>(r)
  14. })
  15. describe('should support markRaw', () => {
  16. class Test<T> {
  17. item = {} as Ref<T>
  18. }
  19. const test = new Test<number>()
  20. const plain = {
  21. ref: ref(1)
  22. }
  23. const r = reactive({
  24. class: {
  25. raw: markRaw(test),
  26. reactive: test
  27. },
  28. plain: {
  29. raw: markRaw(plain),
  30. reactive: plain
  31. }
  32. })
  33. expectType<Test<number>>(r.class.raw)
  34. // @ts-expect-error it should unwrap
  35. expectType<Test<number>>(r.class.reactive)
  36. expectType<Ref<number>>(r.plain.raw.ref)
  37. // @ts-expect-error it should unwrap
  38. expectType<Ref<number>>(r.plain.reactive.ref)
  39. })
  40. describe('shallowReadonly ref unwrap', () => {
  41. const r = shallowReadonly({ count: { n: ref(1) } })
  42. // @ts-expect-error
  43. r.count = 2
  44. expectType<Ref>(r.count.n)
  45. r.count.n.value = 123
  46. })
  47. // #3819
  48. describe('should unwrap tuple correctly', () => {
  49. const readonlyTuple = [ref(0)] as const
  50. const reactiveReadonlyTuple = reactive(readonlyTuple)
  51. expectType<Ref<number>>(reactiveReadonlyTuple[0])
  52. const tuple: [Ref<number>] = [ref(0)]
  53. const reactiveTuple = reactive(tuple)
  54. expectType<Ref<number>>(reactiveTuple[0])
  55. })
  56. describe('should unwrap Map correctly', () => {
  57. const map = reactive(new Map<string, Ref<number>>())
  58. expectType<Ref<number>>(map.get('a')!)
  59. const map2 = reactive(new Map<string, { wrap: Ref<number> }>())
  60. expectType<number>(map2.get('a')!.wrap)
  61. const wm = reactive(new WeakMap<object, Ref<number>>())
  62. expectType<Ref<number>>(wm.get({})!)
  63. const wm2 = reactive(new WeakMap<object, { wrap: Ref<number> }>())
  64. expectType<number>(wm2.get({})!.wrap)
  65. })
  66. describe('should unwrap Set correctly', () => {
  67. const set = reactive(new Set<Ref<number>>())
  68. expectType<Set<Ref<number>>>(set)
  69. const set2 = reactive(new Set<{ wrap: Ref<number> }>())
  70. expectType<Set<{ wrap: number }>>(set2)
  71. const ws = reactive(new WeakSet<Ref<number>>())
  72. expectType<WeakSet<Ref<number>>>(ws)
  73. const ws2 = reactive(new WeakSet<{ wrap: Ref<number> }>())
  74. expectType<WeakSet<{ wrap: number }>>(ws2)
  75. })