ref.test-d.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import { expectType } from 'tsd'
  2. import { Ref, ref, isRef, unref, reactive } 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. // ref boolean
  20. const falseRef = ref(false)
  21. expectType<Ref<boolean>>(falseRef)
  22. expectType<boolean>(falseRef.value)
  23. // ref true
  24. const trueRef = ref<true>(true)
  25. expectType<Ref<true>>(trueRef)
  26. expectType<true>(trueRef.value)
  27. // tuple
  28. expectType<[number, string]>(unref(ref([1, '1'])))
  29. interface IteratorFoo {
  30. [Symbol.iterator]: any
  31. }
  32. // with symbol
  33. expectType<Ref<IteratorFoo | null | undefined>>(
  34. ref<IteratorFoo | null | undefined>()
  35. )
  36. }
  37. plainType(1)
  38. function bailType(arg: HTMLElement | Ref<HTMLElement>) {
  39. // ref coercing
  40. const coerced = ref(arg)
  41. expectType<Ref<HTMLElement>>(coerced)
  42. // isRef as type guard
  43. if (isRef(arg)) {
  44. expectType<Ref<HTMLElement>>(arg)
  45. }
  46. // ref unwrapping
  47. expectType<HTMLElement>(unref(arg))
  48. // ref inner type should be unwrapped
  49. const nestedRef = ref({ foo: ref(document.createElement('DIV')) })
  50. expectType<Ref<{ foo: HTMLElement }>>(nestedRef)
  51. expectType<{ foo: HTMLElement }>(nestedRef.value)
  52. }
  53. const el = document.createElement('DIV')
  54. bailType(el)
  55. function withSymbol() {
  56. const customSymbol = Symbol()
  57. const obj = {
  58. [Symbol.asyncIterator]: { a: 1 },
  59. [Symbol.unscopables]: { b: '1' },
  60. [customSymbol]: { c: [1, 2, 3] }
  61. }
  62. const objRef = ref(obj)
  63. expectType<{ a: number }>(objRef.value[Symbol.asyncIterator])
  64. expectType<{ b: string }>(objRef.value[Symbol.unscopables])
  65. expectType<{ c: Array<number> }>(objRef.value[customSymbol])
  66. }
  67. withSymbol()
  68. const state = reactive({
  69. foo: {
  70. value: 1,
  71. label: 'bar'
  72. }
  73. })
  74. expectType<string>(state.foo.label)