watch.test-d.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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, string, number]>(values)
  12. expectType<[string, 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, string, number]>(values)
  32. expectType<[string | undefined, string | undefined, number | undefined]>(
  33. oldValues
  34. )
  35. },
  36. { immediate: true }
  37. )
  38. // const array
  39. watch(
  40. [source, source2, source3] as const,
  41. (values, oldValues) => {
  42. expectType<Readonly<[string, string, number]>>(values)
  43. expectType<
  44. Readonly<[string | undefined, string | undefined, number | undefined]>
  45. >(oldValues)
  46. },
  47. { immediate: true }
  48. )
  49. // should provide correct ref.value inner type to callbacks
  50. const nestedRefSource = ref({
  51. foo: ref(1)
  52. })
  53. watch(nestedRefSource, (v, ov) => {
  54. expectType<{ foo: number }>(v)
  55. expectType<{ foo: number }>(ov)
  56. })
  57. const someRef = ref({ test: 'test' })
  58. const otherRef = ref({ a: 'b' })
  59. watch([someRef, otherRef], values => {
  60. const value1 = values[0]
  61. // no type error
  62. console.log(value1.test)
  63. const value2 = values[1]
  64. // no type error
  65. console.log(value2.a)
  66. })