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

Type of watch() doesn't take first run into account #719

Closed
jacekkarczmarczyk opened this issue Feb 13, 2020 · 3 comments
Closed

Type of watch() doesn't take first run into account #719

jacekkarczmarczyk opened this issue Feb 13, 2020 · 3 comments

Comments

@jacekkarczmarczyk
Copy link
Contributor

jacekkarczmarczyk commented Feb 13, 2020

Version

3.0.0-alpha.4

Reproduction link

https://codepen.io/jkarczm/pen/ZEYgEXd?editors=0011

Steps to reproduce

import { ref, watch } from "vue";

const r = ref('foo')

watch(r, (_, oldVal) => console.log(oldVal))

watch callback is defined as

(value: T, oldValue: T, onCleanup: CleanupRegistrator) => any

https://github.com/vuejs/vue-next/blob/master/packages/runtime-core/src/apiWatch.ts#L40-L44

It means that in this case it will be

(value: string, oldValue: string, onCleanup: CleanupRegistrator) => any

However on the first run oldVal is undefined.

What is expected?

When I want to use oldVal, for example console.log(oldVal.length) I should be warned by TS that the value can be undefined

What is actually happening?

No warning

@jacekkarczmarczyk jacekkarczmarczyk changed the title Typing of watch() doesn't not take first run into account Type of watch() doesn't take first run into account Feb 13, 2020
@ShenQingchuan
Copy link

Do you mean that this is supposed to be like this ?

export type WatchCallback<T = any> = (
  value: T,
  oldValue: T | undefined,
  onCleanup: CleanupRegistrator
) => any

@jacekkarczmarczyk
Copy link
Contributor Author

The problem with this solution is that oldValue can be unnecessarily undefined for consecutive calls, but to be honest I have no idea if there is a different way to solve it.

@KaelWD
Copy link
Contributor

KaelWD commented Feb 13, 2020

Presumably you'd be checking that anyway with a type guard so undefined would be removed.

Also if options.lazy === true then oldValue should be T

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants