ref.test-d.ts 12 KB

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