ref.test-d.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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. })
  158. // computed
  159. describe('allow computed getter and setter types to be unrelated', () => {
  160. const obj = ref({
  161. name: 'foo',
  162. })
  163. const c = computed({
  164. get() {
  165. return JSON.stringify(obj.value)
  166. },
  167. set(val: typeof obj.value) {
  168. obj.value = val
  169. },
  170. })
  171. c.value = { name: 'bar' } // object
  172. expectType<string>(c.value)
  173. })
  174. // shallowRef
  175. type Status = 'initial' | 'ready' | 'invalidating'
  176. const shallowStatus = shallowRef<Status>('initial')
  177. if (shallowStatus.value === 'initial') {
  178. expectType<Ref<Status>>(shallowStatus)
  179. expectType<Status>(shallowStatus.value)
  180. shallowStatus.value = 'invalidating'
  181. }
  182. const refStatus = ref<Status>('initial')
  183. if (refStatus.value === 'initial') {
  184. expectType<Ref<Status>>(shallowStatus)
  185. expectType<Status>(shallowStatus.value)
  186. refStatus.value = 'invalidating'
  187. }
  188. {
  189. const shallow = shallowRef(1)
  190. expectType<Ref<number>>(shallow)
  191. expectType<ShallowRef<number>>(shallow)
  192. }
  193. {
  194. //#7852
  195. type Steps = { step: '1' } | { step: '2' }
  196. const shallowUnionGenParam = shallowRef<Steps>({ step: '1' })
  197. const shallowUnionAsCast = shallowRef({ step: '1' } as Steps)
  198. expectType<IsUnion<typeof shallowUnionGenParam>>(false)
  199. expectType<IsUnion<typeof shallowUnionAsCast>>(false)
  200. }
  201. {
  202. // any value should return Ref<any>, not any
  203. const a = shallowRef(1 as any)
  204. expectType<IsAny<typeof a>>(false)
  205. }
  206. describe('shallowRef with generic', <T extends { name: string }>() => {
  207. const r = {} as T
  208. const s = shallowRef(r)
  209. expectType<string>(s.value.name)
  210. expectType<ShallowRef<T>>(shallowRef(r))
  211. const rr = {} as MaybeRef<T>
  212. // should at least allow casting
  213. const ss = shallowRef(rr) as Ref<T> | ShallowRef<T>
  214. expectType<string>(ss.value.name)
  215. })
  216. {
  217. // should return ShallowRef<T> | Ref<T>, not ShallowRef<T | Ref<T>>
  218. expectType<ShallowRef<{ name: string }> | Ref<{ name: string }>>(
  219. shallowRef({} as MaybeRef<{ name: string }>),
  220. )
  221. expectType<ShallowRef<number> | Ref<string[]> | ShallowRef<string>>(
  222. shallowRef('' as Ref<string[]> | string | number),
  223. )
  224. }
  225. // proxyRefs: should return `reactive` directly
  226. const r1 = reactive({
  227. k: 'v',
  228. })
  229. const p1 = proxyRefs(r1)
  230. expectType<typeof r1>(p1)
  231. // proxyRefs: `ShallowUnwrapRef`
  232. const r2 = {
  233. a: ref(1),
  234. c: computed(() => 1),
  235. u: undefined,
  236. obj: {
  237. k: ref('foo'),
  238. },
  239. union: Math.random() > 0 - 5 ? ref({ name: 'yo' }) : null,
  240. }
  241. const p2 = proxyRefs(r2)
  242. expectType<number>(p2.a)
  243. expectType<number>(p2.c)
  244. expectType<undefined>(p2.u)
  245. expectType<Ref<string>>(p2.obj.k)
  246. expectType<{ name: string } | null>(p2.union)
  247. // toRef and toRefs
  248. {
  249. const obj: {
  250. a: number
  251. b: Ref<number>
  252. c: number | string
  253. } = {
  254. a: 1,
  255. b: ref(1),
  256. c: 1,
  257. }
  258. // toRef
  259. expectType<Ref<number>>(toRef(obj, 'a'))
  260. expectType<Ref<number>>(toRef(obj, 'b'))
  261. // Should not distribute Refs over union
  262. expectType<Ref<number | string>>(toRef(obj, 'c'))
  263. expectType<Ref<number>>(toRef(() => 123))
  264. expectType<Ref<number | string>>(toRef(() => obj.c))
  265. const r = toRef(() => 123)
  266. // @ts-expect-error
  267. r.value = 234
  268. // toRefs
  269. expectType<{
  270. a: Ref<number>
  271. b: Ref<number>
  272. // Should not distribute Refs over union
  273. c: Ref<number | string>
  274. }>(toRefs(obj))
  275. // Both should not do any unwrapping
  276. const someReactive = shallowReactive({
  277. a: {
  278. b: ref(42),
  279. },
  280. })
  281. const toRefResult = toRef(someReactive, 'a')
  282. const toRefsResult = toRefs(someReactive)
  283. expectType<Ref<number>>(toRefResult.value.b)
  284. expectType<Ref<number>>(toRefsResult.a.value.b)
  285. // #5188
  286. const props = { foo: 1 } as { foo: any }
  287. const { foo } = toRefs(props)
  288. expectType<Ref<any>>(foo)
  289. }
  290. // toRef default value
  291. {
  292. const obj: { x?: number } = {}
  293. const x = toRef(obj, 'x', 1)
  294. expectType<Ref<number>>(x)
  295. }
  296. // readonly() + ref()
  297. expectType<Readonly<Ref<number>>>(readonly(ref(1)))
  298. // #2687
  299. interface AppData {
  300. state: 'state1' | 'state2' | 'state3'
  301. }
  302. const data: ToRefs<AppData> = toRefs(
  303. reactive({
  304. state: 'state1',
  305. }),
  306. )
  307. switch (data.state.value) {
  308. case 'state1':
  309. data.state.value = 'state2'
  310. break
  311. case 'state2':
  312. data.state.value = 'state3'
  313. break
  314. case 'state3':
  315. data.state.value = 'state1'
  316. break
  317. }
  318. // #3954
  319. function testUnrefGenerics<T>(p: T | Ref<T>) {
  320. expectType<T>(unref(p))
  321. }
  322. testUnrefGenerics(1)
  323. // #4771
  324. describe('shallow reactive in reactive', () => {
  325. const baz = reactive({
  326. foo: shallowReactive({
  327. a: {
  328. b: ref(42),
  329. },
  330. }),
  331. })
  332. const foo = toRef(baz, 'foo')
  333. expectType<Ref<number>>(foo.value.a.b)
  334. expectType<number>(foo.value.a.b.value)
  335. })
  336. describe('shallow ref in reactive', () => {
  337. const x = reactive({
  338. foo: shallowRef({
  339. bar: {
  340. baz: ref(123),
  341. qux: reactive({
  342. z: ref(123),
  343. }),
  344. },
  345. }),
  346. })
  347. expectType<Ref<number>>(x.foo.bar.baz)
  348. expectType<number>(x.foo.bar.qux.z)
  349. })
  350. describe('ref in shallow ref', () => {
  351. const x = shallowRef({
  352. a: ref(123),
  353. })
  354. expectType<Ref<number>>(x.value.a)
  355. })
  356. describe('reactive in shallow ref', () => {
  357. const x = shallowRef({
  358. a: reactive({
  359. b: ref(0),
  360. }),
  361. })
  362. expectType<number>(x.value.a.b)
  363. })
  364. describe('toRef <-> toValue', () => {
  365. function foo(
  366. a: MaybeRef<string>,
  367. b: () => string,
  368. c: MaybeRefOrGetter<string>,
  369. d: ComputedRef<string>,
  370. ) {
  371. const r = toRef(a)
  372. expectType<Ref<string>>(r)
  373. // writable
  374. r.value = 'foo'
  375. const rb = toRef(b)
  376. expectType<Readonly<Ref<string>>>(rb)
  377. // @ts-expect-error ref created from getter should be readonly
  378. rb.value = 'foo'
  379. const rc = toRef(c)
  380. expectType<Readonly<Ref<string> | Ref<string>>>(rc)
  381. // @ts-expect-error ref created from MaybeReadonlyRef should be readonly
  382. rc.value = 'foo'
  383. const rd = toRef(d)
  384. expectType<ComputedRef<string>>(rd)
  385. // @ts-expect-error ref created from computed ref should be readonly
  386. rd.value = 'foo'
  387. expectType<string>(toValue(a))
  388. expectType<string>(toValue(b))
  389. expectType<string>(toValue(c))
  390. expectType<string>(toValue(d))
  391. return {
  392. r: toValue(r),
  393. rb: toValue(rb),
  394. rc: toValue(rc),
  395. rd: toValue(rd),
  396. }
  397. }
  398. expectType<{
  399. r: string
  400. rb: string
  401. rc: string
  402. rd: string
  403. }>(
  404. foo(
  405. 'foo',
  406. () => 'bar',
  407. ref('baz'),
  408. computed(() => 'hi'),
  409. ),
  410. )
  411. })
  412. // unref
  413. // #8747
  414. declare const unref1: number | Ref<number> | ComputedRef<number>
  415. expectType<number>(unref(unref1))
  416. // #11356
  417. declare const unref2:
  418. | MaybeRef<string>
  419. | ShallowRef<string>
  420. | ComputedRef<string>
  421. | WritableComputedRef<string>
  422. expectType<string>(unref(unref2))
  423. // toValue
  424. expectType<number>(toValue(unref1))
  425. expectType<string>(toValue(unref2))
  426. // useTemplateRef
  427. const tRef = useTemplateRef('foo')
  428. expectType<Readonly<ShallowRef<unknown>>>(tRef)
  429. const tRef2 = useTemplateRef<HTMLElement>('bar')
  430. expectType<Readonly<ShallowRef<HTMLElement | null>>>(tRef2)