ref.test-d.ts 2.1 KB

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