watch-test.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { ref, computed, watch } from '../../index'
  2. import { expectType } from '../utils'
  3. const source = ref('foo')
  4. const source2 = computed(() => source.value)
  5. const source3 = () => 1
  6. // lazy watcher will have consistent types for oldValue.
  7. watch(source, (value, oldValue) => {
  8. expectType<string>(value)
  9. expectType<string>(oldValue)
  10. })
  11. watch([source, source2, source3], (values, oldValues) => {
  12. expectType<[string, string, number]>(values)
  13. expectType<[string, string, number]>(oldValues)
  14. })
  15. // const array
  16. watch([source, source2, source3] as const, (values, oldValues) => {
  17. expectType<Readonly<[string, string, number]>>(values)
  18. expectType<Readonly<[string, string, number]>>(oldValues)
  19. })
  20. // immediate watcher's oldValue will be undefined on first run.
  21. watch(
  22. source,
  23. (value, oldValue) => {
  24. expectType<string>(value)
  25. expectType<string | undefined>(oldValue)
  26. },
  27. { immediate: true }
  28. )
  29. watch(
  30. [source, source2, source3],
  31. (values, oldValues) => {
  32. expectType<[string, string, number]>(values)
  33. expectType<[string | undefined, string | undefined, number | undefined]>(
  34. oldValues
  35. )
  36. },
  37. { immediate: true }
  38. )
  39. // const array
  40. watch(
  41. [source, source2, source3] as const,
  42. (values, oldValues) => {
  43. expectType<Readonly<[string, string, number]>>(values)
  44. expectType<
  45. Readonly<[string | undefined, string | undefined, number | undefined]>
  46. >(oldValues)
  47. },
  48. { immediate: true }
  49. )
  50. // should provide correct ref.value inner type to callbacks
  51. const nestedRefSource = ref({
  52. foo: ref(1)
  53. })
  54. watch(nestedRefSource, (v, ov) => {
  55. expectType<{ foo: number }>(v)
  56. expectType<{ foo: number }>(ov)
  57. })
  58. const someRef = ref({ test: 'test' })
  59. const otherRef = ref({ a: 'b' })
  60. watch([someRef, otherRef], values => {
  61. const value1 = values[0]
  62. // no type error
  63. console.log(value1.test)
  64. const value2 = values[1]
  65. // no type error
  66. console.log(value2.a)
  67. })