ref.test-d.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. import {
  2. type ComputedRef,
  3. type MaybeRef,
  4. type MaybeRefOrGetter,
  5. type Ref,
  6. type ShallowRef,
  7. type ToRefs,
  8. computed,
  9. isRef,
  10. proxyRefs,
  11. reactive,
  12. readonly,
  13. ref,
  14. shallowReactive,
  15. shallowRef,
  16. toRef,
  17. toRefs,
  18. toValue,
  19. unref,
  20. } from 'vue'
  21. import { type IsAny, type IsUnion, describe, expectType } from './utils'
  22. function plainType(arg: number | Ref<number>) {
  23. // ref coercing
  24. const coerced = ref(arg)
  25. expectType<Ref<number>>(coerced)
  26. // isRef as type guard
  27. if (isRef(arg)) {
  28. expectType<Ref<number>>(arg)
  29. }
  30. // ref unwrapping
  31. expectType<number>(unref(arg))
  32. expectType<number>(toValue(arg))
  33. expectType<number>(toValue(() => 123))
  34. // ref inner type should be unwrapped
  35. const nestedRef = ref({
  36. foo: ref(1),
  37. })
  38. expectType<{ foo: number }>(nestedRef.value)
  39. // ref boolean
  40. const falseRef = ref(false)
  41. expectType<Ref<boolean>>(falseRef)
  42. expectType<boolean>(falseRef.value)
  43. // ref true
  44. const trueRef = ref<true>(true)
  45. expectType<Ref<true>>(trueRef)
  46. expectType<true>(trueRef.value)
  47. // tuple
  48. expectType<[number, string]>(unref(ref([1, '1'])))
  49. interface IteratorFoo {
  50. [Symbol.iterator]: any
  51. }
  52. // with symbol
  53. expectType<Ref<IteratorFoo | null | undefined>>(
  54. ref<IteratorFoo | null | undefined>(),
  55. )
  56. // should not unwrap ref inside arrays
  57. const arr = ref([1, new Map<string, any>(), ref('1')]).value
  58. const value = arr[0]
  59. if (isRef(value)) {
  60. expectType<Ref>(value)
  61. } else if (typeof value === 'number') {
  62. expectType<number>(value)
  63. } else {
  64. // should narrow down to Map type
  65. // and not contain any Ref type
  66. expectType<Map<string, any>>(value)
  67. }
  68. // should still unwrap in objects nested in arrays
  69. const arr2 = ref([{ a: ref(1) }]).value
  70. expectType<number>(arr2[0].a)
  71. // any value should return Ref<any>, not any
  72. const a = ref(1 as any)
  73. expectType<IsAny<typeof a>>(false)
  74. }
  75. plainType(1)
  76. function bailType(arg: HTMLElement | Ref<HTMLElement>) {
  77. // ref coercing
  78. const coerced = ref(arg)
  79. expectType<Ref<HTMLElement>>(coerced)
  80. // isRef as type guard
  81. if (isRef(arg)) {
  82. expectType<Ref<HTMLElement>>(arg)
  83. }
  84. // ref unwrapping
  85. expectType<HTMLElement>(unref(arg))
  86. // ref inner type should be unwrapped
  87. const nestedRef = ref({ foo: ref(document.createElement('DIV')) })
  88. expectType<Ref<{ foo: HTMLElement }>>(nestedRef)
  89. expectType<{ foo: HTMLElement }>(nestedRef.value)
  90. }
  91. const el = document.createElement('DIV')
  92. bailType(el)
  93. function withSymbol() {
  94. const customSymbol = Symbol()
  95. const obj = {
  96. [Symbol.asyncIterator]: ref(1),
  97. [Symbol.hasInstance]: { a: ref('a') },
  98. [Symbol.isConcatSpreadable]: { b: ref(true) },
  99. [Symbol.iterator]: [ref(1)],
  100. [Symbol.match]: new Set<Ref<number>>(),
  101. [Symbol.matchAll]: new Map<number, Ref<string>>(),
  102. [Symbol.replace]: { arr: [ref('a')] },
  103. [Symbol.search]: { set: new Set<Ref<number>>() },
  104. [Symbol.species]: { map: new Map<number, Ref<string>>() },
  105. [Symbol.split]: new WeakSet<Ref<boolean>>(),
  106. [Symbol.toPrimitive]: new WeakMap<Ref<boolean>, string>(),
  107. [Symbol.toStringTag]: { weakSet: new WeakSet<Ref<boolean>>() },
  108. [Symbol.unscopables]: { weakMap: new WeakMap<Ref<boolean>, string>() },
  109. [customSymbol]: { arr: [ref(1)] },
  110. }
  111. const objRef = ref(obj)
  112. expectType<Ref<number>>(objRef.value[Symbol.asyncIterator])
  113. expectType<{ a: Ref<string> }>(objRef.value[Symbol.hasInstance])
  114. expectType<{ b: Ref<boolean> }>(objRef.value[Symbol.isConcatSpreadable])
  115. expectType<Ref<number>[]>(objRef.value[Symbol.iterator])
  116. expectType<Set<Ref<number>>>(objRef.value[Symbol.match])
  117. expectType<Map<number, Ref<string>>>(objRef.value[Symbol.matchAll])
  118. expectType<{ arr: Ref<string>[] }>(objRef.value[Symbol.replace])
  119. expectType<{ set: Set<Ref<number>> }>(objRef.value[Symbol.search])
  120. expectType<{ map: Map<number, Ref<string>> }>(objRef.value[Symbol.species])
  121. expectType<WeakSet<Ref<boolean>>>(objRef.value[Symbol.split])
  122. expectType<WeakMap<Ref<boolean>, string>>(objRef.value[Symbol.toPrimitive])
  123. expectType<{ weakSet: WeakSet<Ref<boolean>> }>(
  124. objRef.value[Symbol.toStringTag],
  125. )
  126. expectType<{ weakMap: WeakMap<Ref<boolean>, string> }>(
  127. objRef.value[Symbol.unscopables],
  128. )
  129. expectType<{ arr: Ref<number>[] }>(objRef.value[customSymbol])
  130. }
  131. withSymbol()
  132. const state = reactive({
  133. foo: {
  134. value: 1,
  135. label: 'bar',
  136. },
  137. })
  138. expectType<string>(state.foo.label)
  139. describe('ref with generic', <T extends { name: string }>() => {
  140. const r = {} as T
  141. const s = ref(r)
  142. expectType<string>(s.value.name)
  143. const rr = {} as MaybeRef<T>
  144. // should at least allow casting
  145. const ss = ref(rr) as Ref<T>
  146. expectType<string>(ss.value.name)
  147. })
  148. // shallowRef
  149. type Status = 'initial' | 'ready' | 'invalidating'
  150. const shallowStatus = shallowRef<Status>('initial')
  151. if (shallowStatus.value === 'initial') {
  152. expectType<Ref<Status>>(shallowStatus)
  153. expectType<Status>(shallowStatus.value)
  154. shallowStatus.value = 'invalidating'
  155. }
  156. const refStatus = ref<Status>('initial')
  157. if (refStatus.value === 'initial') {
  158. expectType<Ref<Status>>(shallowStatus)
  159. expectType<Status>(shallowStatus.value)
  160. refStatus.value = 'invalidating'
  161. }
  162. {
  163. const shallow = shallowRef(1)
  164. expectType<Ref<number>>(shallow)
  165. expectType<ShallowRef<number>>(shallow)
  166. }
  167. {
  168. //#7852
  169. type Steps = { step: '1' } | { step: '2' }
  170. const shallowUnionGenParam = shallowRef<Steps>({ step: '1' })
  171. const shallowUnionAsCast = shallowRef({ step: '1' } as Steps)
  172. expectType<IsUnion<typeof shallowUnionGenParam>>(false)
  173. expectType<IsUnion<typeof shallowUnionAsCast>>(false)
  174. }
  175. {
  176. // any value should return Ref<any>, not any
  177. const a = shallowRef(1 as any)
  178. expectType<IsAny<typeof a>>(false)
  179. }
  180. describe('shallowRef with generic', <T extends { name: string }>() => {
  181. const r = {} as T
  182. const s = shallowRef(r)
  183. expectType<string>(s.value.name)
  184. expectType<ShallowRef<T>>(shallowRef(r))
  185. const rr = {} as MaybeRef<T>
  186. // should at least allow casting
  187. const ss = shallowRef(rr) as Ref<T> | ShallowRef<T>
  188. expectType<string>(ss.value.name)
  189. })
  190. {
  191. // should return ShallowRef<T> | Ref<T>, not ShallowRef<T | Ref<T>>
  192. expectType<ShallowRef<{ name: string }> | Ref<{ name: string }>>(
  193. shallowRef({} as MaybeRef<{ name: string }>),
  194. )
  195. expectType<ShallowRef<number> | Ref<string[]> | ShallowRef<string>>(
  196. shallowRef('' as Ref<string[]> | string | number),
  197. )
  198. }
  199. // proxyRefs: should return `reactive` directly
  200. const r1 = reactive({
  201. k: 'v',
  202. })
  203. const p1 = proxyRefs(r1)
  204. expectType<typeof r1>(p1)
  205. // proxyRefs: `ShallowUnwrapRef`
  206. const r2 = {
  207. a: ref(1),
  208. c: computed(() => 1),
  209. u: undefined,
  210. obj: {
  211. k: ref('foo'),
  212. },
  213. union: Math.random() > 0 - 5 ? ref({ name: 'yo' }) : null,
  214. }
  215. const p2 = proxyRefs(r2)
  216. expectType<number>(p2.a)
  217. expectType<number>(p2.c)
  218. expectType<undefined>(p2.u)
  219. expectType<Ref<string>>(p2.obj.k)
  220. expectType<{ name: string } | null>(p2.union)
  221. // toRef and toRefs
  222. {
  223. const obj: {
  224. a: number
  225. b: Ref<number>
  226. c: number | string
  227. } = {
  228. a: 1,
  229. b: ref(1),
  230. c: 1,
  231. }
  232. // toRef
  233. expectType<Ref<number>>(toRef(obj, 'a'))
  234. expectType<Ref<number>>(toRef(obj, 'b'))
  235. // Should not distribute Refs over union
  236. expectType<Ref<number | string>>(toRef(obj, 'c'))
  237. expectType<Ref<number>>(toRef(() => 123))
  238. expectType<Ref<number | string>>(toRef(() => obj.c))
  239. const r = toRef(() => 123)
  240. // @ts-expect-error
  241. r.value = 234
  242. // toRefs
  243. expectType<{
  244. a: Ref<number>
  245. b: Ref<number>
  246. // Should not distribute Refs over union
  247. c: Ref<number | string>
  248. }>(toRefs(obj))
  249. // Both should not do any unwrapping
  250. const someReactive = shallowReactive({
  251. a: {
  252. b: ref(42),
  253. },
  254. })
  255. const toRefResult = toRef(someReactive, 'a')
  256. const toRefsResult = toRefs(someReactive)
  257. expectType<Ref<number>>(toRefResult.value.b)
  258. expectType<Ref<number>>(toRefsResult.a.value.b)
  259. // #5188
  260. const props = { foo: 1 } as { foo: any }
  261. const { foo } = toRefs(props)
  262. expectType<Ref<any>>(foo)
  263. }
  264. // toRef default value
  265. {
  266. const obj: { x?: number } = {}
  267. const x = toRef(obj, 'x', 1)
  268. expectType<Ref<number>>(x)
  269. }
  270. // readonly() + ref()
  271. expectType<Readonly<Ref<number>>>(readonly(ref(1)))
  272. // #2687
  273. interface AppData {
  274. state: 'state1' | 'state2' | 'state3'
  275. }
  276. const data: ToRefs<AppData> = toRefs(
  277. reactive({
  278. state: 'state1',
  279. }),
  280. )
  281. switch (data.state.value) {
  282. case 'state1':
  283. data.state.value = 'state2'
  284. break
  285. case 'state2':
  286. data.state.value = 'state3'
  287. break
  288. case 'state3':
  289. data.state.value = 'state1'
  290. break
  291. }
  292. // #3954
  293. function testUnrefGenerics<T>(p: T | Ref<T>) {
  294. expectType<T>(unref(p))
  295. }
  296. testUnrefGenerics(1)
  297. // #4771
  298. describe('shallow reactive in reactive', () => {
  299. const baz = reactive({
  300. foo: shallowReactive({
  301. a: {
  302. b: ref(42),
  303. },
  304. }),
  305. })
  306. const foo = toRef(baz, 'foo')
  307. expectType<Ref<number>>(foo.value.a.b)
  308. expectType<number>(foo.value.a.b.value)
  309. })
  310. describe('shallow ref in reactive', () => {
  311. const x = reactive({
  312. foo: shallowRef({
  313. bar: {
  314. baz: ref(123),
  315. qux: reactive({
  316. z: ref(123),
  317. }),
  318. },
  319. }),
  320. })
  321. expectType<Ref<number>>(x.foo.bar.baz)
  322. expectType<number>(x.foo.bar.qux.z)
  323. })
  324. describe('ref in shallow ref', () => {
  325. const x = shallowRef({
  326. a: ref(123),
  327. })
  328. expectType<Ref<number>>(x.value.a)
  329. })
  330. describe('reactive in shallow ref', () => {
  331. const x = shallowRef({
  332. a: reactive({
  333. b: ref(0),
  334. }),
  335. })
  336. expectType<number>(x.value.a.b)
  337. })
  338. describe('toRef <-> toValue', () => {
  339. function foo(
  340. a: MaybeRef<string>,
  341. b: () => string,
  342. c: MaybeRefOrGetter<string>,
  343. d: ComputedRef<string>,
  344. ) {
  345. const r = toRef(a)
  346. expectType<Ref<string>>(r)
  347. // writable
  348. r.value = 'foo'
  349. const rb = toRef(b)
  350. expectType<Readonly<Ref<string>>>(rb)
  351. // @ts-expect-error ref created from getter should be readonly
  352. rb.value = 'foo'
  353. const rc = toRef(c)
  354. expectType<Readonly<Ref<string> | Ref<string>>>(rc)
  355. // @ts-expect-error ref created from MaybeReadonlyRef should be readonly
  356. rc.value = 'foo'
  357. const rd = toRef(d)
  358. expectType<ComputedRef<string>>(rd)
  359. // @ts-expect-error ref created from computed ref should be readonly
  360. rd.value = 'foo'
  361. expectType<string>(toValue(a))
  362. expectType<string>(toValue(b))
  363. expectType<string>(toValue(c))
  364. expectType<string>(toValue(d))
  365. return {
  366. r: toValue(r),
  367. rb: toValue(rb),
  368. rc: toValue(rc),
  369. rd: toValue(rd),
  370. }
  371. }
  372. expectType<{
  373. r: string
  374. rb: string
  375. rc: string
  376. rd: string
  377. }>(
  378. foo(
  379. 'foo',
  380. () => 'bar',
  381. ref('baz'),
  382. computed(() => 'hi'),
  383. ),
  384. )
  385. })