Skip to content

shallowRef's return type should match ref's #12978

Closed
@simlevesque

Description

@simlevesque

Version

2.7.14

Reproduction link

codesandbox.io

(this is a typescript bug, it's not visible on the sfc playground)

Steps to reproduce

  • Use shallowRef with a generic type params that's a union : shallowRef<{a:1} | {b:2}>({a:1})
  • Or use shallowRef and specify argument's type with as: shallowRef({a:1} as {a:1} | {b:2})

What is expected?

The return type should be ShallowRef<{a:1} | {b:2}>.

What is actually happening?

The return type is ShallowRef<{a:1}> | ShallowRef<{b:2}>


This breaks Vue's watch function. The first argument of watch's callback becomes a Ref instead of the value, which will cause a runtime error because Property 'value' does not exist on type '{ a: 1; } | { b: 2; }'

The reproduction link provides a good example of this. If you have any questions just ask me.

I've fixed the issue on my fork and the CI actions completed successfully.

You need to change
function shallowRef<T extends object>(value: T): T extends Ref ? T : ShallowRef<T>;

to
function shallowRef<T extends object>(value: T): [T] extends [Ref] ? T : ShallowRef<T>;

This matches ref's type:
function ref<T extends object>(value: T): [T] extends [Ref] ? T : Ref<UnwrapRef<T>>;

This issue is the same issue as vuejs/core#7852

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions