ref.test-d.ts 12 KB

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