Skip to content

Commit 9a57158

Browse files
fix(types): fix shallowRef type error (#9839)
1 parent e70f4c4 commit 9a57158

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

packages/dts-test/ref.test-d.ts

+15-3
Original file line numberDiff line numberDiff line change
@@ -201,11 +201,23 @@ if (refStatus.value === 'initial') {
201201
expectType<IsAny<typeof a>>(false)
202202
}
203203

204-
describe('shallowRef with generic', <T>() => {
205-
const r = ref({}) as MaybeRef<T>
206-
expectType<ShallowRef<T> | Ref<T>>(shallowRef(r))
204+
describe('shallowRef with generic', <T extends { name: string }>() => {
205+
const r = {} as T
206+
const s = shallowRef(r)
207+
expectType<string>(s.value.name)
208+
expectType<ShallowRef<T>>(shallowRef(r))
207209
})
208210

211+
{
212+
// should return ShallowRef<T> | Ref<T>, not ShallowRef<T | Ref<T>>
213+
expectType<ShallowRef<{ name: string }> | Ref<{ name: string }>>(
214+
shallowRef({} as MaybeRef<{ name: string }>)
215+
)
216+
expectType<ShallowRef<number> | Ref<string[]> | ShallowRef<string>>(
217+
shallowRef('' as Ref<string[]> | string | number)
218+
)
219+
}
220+
209221
// proxyRefs: should return `reactive` directly
210222
const r1 = reactive({
211223
k: 'v'

packages/reactivity/src/ref.ts

+7-3
Original file line numberDiff line numberDiff line change
@@ -114,9 +114,13 @@ export type ShallowRef<T = any> = Ref<T> & { [ShallowRefMarker]?: true }
114114
* @param value - The "inner value" for the shallow ref.
115115
* @see {@link https://vuejs.org/api/reactivity-advanced.html#shallowref}
116116
*/
117-
export function shallowRef<T>(value: MaybeRef<T>): Ref<T> | ShallowRef<T>
118-
export function shallowRef<T extends Ref>(value: T): T
119-
export function shallowRef<T>(value: T): ShallowRef<T>
117+
export function shallowRef<T>(
118+
value: T
119+
): Ref extends T
120+
? T extends Ref
121+
? IfAny<T, ShallowRef<T>, T>
122+
: ShallowRef<T>
123+
: ShallowRef<T>
120124
export function shallowRef<T = any>(): ShallowRef<T | undefined>
121125
export function shallowRef(value?: unknown) {
122126
return createRef(value, true)

0 commit comments

Comments
 (0)