watch.test-d.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { ref, computed, watch } from './index'
  2. import { expectType } from 'tsd'
  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 | number)[]>(values)
  13. expectType<(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 | number)[]>(values)
  33. expectType<(string | number | undefined)[]>(oldValues)
  34. },
  35. { immediate: true }
  36. )
  37. // const array
  38. watch(
  39. [source, source2, source3] as const,
  40. (values, oldValues) => {
  41. expectType<Readonly<[string, string, number]>>(values)
  42. expectType<
  43. Readonly<[string | undefined, string | undefined, number | undefined]>
  44. >(oldValues)
  45. },
  46. { immediate: true }
  47. )