watch.test-d.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. )
  48. // should provide correct ref.value inner type to callbacks
  49. const nestedRefSource = ref({
  50. foo: ref(1)
  51. })
  52. watch(nestedRefSource, (v, ov) => {
  53. expectType<{ foo: number }>(v)
  54. expectType<{ foo: number }>(ov)
  55. })