Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
simlevesque opened this issue Mar 7, 2023 · 2 comments · Fixed by #12979
Closed

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

simlevesque opened this issue Mar 7, 2023 · 2 comments · Fixed by #12979

Comments

@simlevesque
Copy link
Contributor

simlevesque commented Mar 7, 2023

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

@simlevesque
Copy link
Contributor Author

I've added a better reproduction of the error to show it will lead to runtime error.

@wagonwangqi
Copy link

奥利给

simlevesque added a commit to simlevesque/vue that referenced this issue Mar 9, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants