]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
fix(types): fix `shallowRef` type error (#9839)
author丶远方 <yangpanteng@gmail.com>
Sat, 16 Dec 2023 05:45:01 +0000 (13:45 +0800)
committerGitHub <noreply@github.com>
Sat, 16 Dec 2023 05:45:01 +0000 (13:45 +0800)
packages/dts-test/ref.test-d.ts
packages/reactivity/src/ref.ts

index a467c446d0a39d66d49dfefc94e653f007f48546..f66ff9269079472a688587dfd5422b7ae49dc68e 100644 (file)
@@ -201,11 +201,23 @@ if (refStatus.value === 'initial') {
   expectType<IsAny<typeof a>>(false)
 }
 
-describe('shallowRef with generic', <T>() => {
-  const r = ref({}) as MaybeRef<T>
-  expectType<ShallowRef<T> | Ref<T>>(shallowRef(r))
+describe('shallowRef with generic', <T extends { name: string }>() => {
+  const r = {} as T
+  const s = shallowRef(r)
+  expectType<string>(s.value.name)
+  expectType<ShallowRef<T>>(shallowRef(r))
 })
 
+{
+  // should return ShallowRef<T> | Ref<T>, not ShallowRef<T | Ref<T>>
+  expectType<ShallowRef<{ name: string }> | Ref<{ name: string }>>(
+    shallowRef({} as MaybeRef<{ name: string }>)
+  )
+  expectType<ShallowRef<number> | Ref<string[]> | ShallowRef<string>>(
+    shallowRef('' as Ref<string[]> | string | number)
+  )
+}
+
 // proxyRefs: should return `reactive` directly
 const r1 = reactive({
   k: 'v'
index f068844100e86bcfbcfe492e46e846c8ae0b7540..a85c79c0bc63fd332c95e1fdfb9f9f065f07c482 100644 (file)
@@ -114,9 +114,13 @@ export type ShallowRef<T = any> = Ref<T> & { [ShallowRefMarker]?: true }
  * @param value - The "inner value" for the shallow ref.
  * @see {@link https://vuejs.org/api/reactivity-advanced.html#shallowref}
  */
-export function shallowRef<T>(value: MaybeRef<T>): Ref<T> | ShallowRef<T>
-export function shallowRef<T extends Ref>(value: T): T
-export function shallowRef<T>(value: T): ShallowRef<T>
+export function shallowRef<T>(
+  value: T
+): Ref extends T
+  ? T extends Ref
+    ? IfAny<T, ShallowRef<T>, T>
+    : ShallowRef<T>
+  : ShallowRef<T>
 export function shallowRef<T = any>(): ShallowRef<T | undefined>
 export function shallowRef(value?: unknown) {
   return createRef(value, true)