watch.test-d.ts 1.5 KB

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