ref.test-d.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { expectType } from 'tsd'
  2. import { Ref, ref, isRef, unref } from './index'
  3. function plainType(arg: number | Ref<number>) {
  4. // ref coercing
  5. const coerced = ref(arg)
  6. expectType<Ref<number>>(coerced)
  7. // isRef as type guard
  8. if (isRef(arg)) {
  9. expectType<Ref<number>>(arg)
  10. }
  11. // ref unwrapping
  12. expectType<number>(unref(arg))
  13. // ref inner type should be unwrapped
  14. const nestedRef = ref({
  15. foo: ref(1)
  16. })
  17. expectType<Ref<{ foo: number }>>(nestedRef)
  18. expectType<{ foo: number }>(nestedRef.value)
  19. // tuple
  20. expectType<[number, string]>(unref(ref([1, '1'])))
  21. interface IteratorFoo {
  22. [Symbol.iterator]: any
  23. }
  24. // with symbol
  25. expectType<Ref<IteratorFoo | null | undefined>>(
  26. ref<IteratorFoo | null | undefined>()
  27. )
  28. }
  29. plainType(1)
  30. function bailType(arg: HTMLElement | Ref<HTMLElement>) {
  31. // ref coercing
  32. const coerced = ref(arg)
  33. expectType<Ref<HTMLElement>>(coerced)
  34. // isRef as type guard
  35. if (isRef(arg)) {
  36. expectType<Ref<HTMLElement>>(arg)
  37. }
  38. // ref unwrapping
  39. expectType<HTMLElement>(unref(arg))
  40. // ref inner type should be unwrapped
  41. const nestedRef = ref({ foo: ref(document.createElement('DIV')) })
  42. expectType<Ref<{ foo: HTMLElement }>>(nestedRef)
  43. expectType<{ foo: HTMLElement }>(nestedRef.value)
  44. }
  45. const el = document.createElement('DIV')
  46. bailType(el)
  47. function withSymbol() {
  48. const customSymbol = Symbol()
  49. const obj = {
  50. [Symbol.asyncIterator]: { a: 1 },
  51. [Symbol.unscopables]: { b: '1' },
  52. [customSymbol]: { c: [1, 2, 3] }
  53. }
  54. const objRef = ref(obj)
  55. expectType<{ a: number }>(objRef.value[Symbol.asyncIterator])
  56. expectType<{ b: string }>(objRef.value[Symbol.unscopables])
  57. expectType<{ c: Array<number> }>(objRef.value[customSymbol])
  58. }
  59. withSymbol()