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

[Vue2.7] A type error. method can't be called in option "data" #12944

Open
timongh opened this issue Jan 27, 2023 · 5 comments
Open

[Vue2.7] A type error. method can't be called in option "data" #12944

timongh opened this issue Jan 27, 2023 · 5 comments

Comments

@timongh
Copy link

timongh commented Jan 27, 2023

Version

2.7.14

Reproduction link

github.com

Steps to reproduce

  1. run pnpm install(or use npm, yarn)
  2. run pnpm type-check(actual command is vue-tsc --noEmit)

What is expected?

no error

What is actually happening?

An error was reported: The method in option methods could not be found in the option data

src/main.ts:6:19 - error TS2339: Property 'method1' does not exist on type 'CreateComponentPublicInstance<{}, {}, {}, {}, {}, ComponentOptionsMixin,
 ComponentOptionsMixin, {}, {}, {}, false, OptionTypesType<{}, {}, {}, {}, {}, {}>, {}, {}, {}, {}, {}, {}>'.

6       data1: this.method1(),
                    ~~~~~~~

The main code in the repository is:

defineComponent({
  data() {
    return {
      data1: this.method1(),
    }
  },
  methods: {
    method1(): number {
      return 1
    }
  }
})
@zhixinghy
Copy link

image

@posva
Copy link
Member

posva commented Feb 2, 2023

This might be the same issue of computed referencing other computed properties needing an explicit type annotation. Have you tried this:

defineComponent({
  data(): { data1: number } {
    return {
      data1: this.method1(),
    }
  },
  methods: {
    method1(): number {
      return 1
    }
  }
})

@timongh
Copy link
Author

timongh commented Feb 2, 2023

@posva I just tried it and the problem still exists

@bill-mark
Copy link

Illegal usage
The object must be plain: native objects such as browser API objects and prototype properties are ignored.

@rudyxu1102
Copy link

rudyxu1102 commented Feb 14, 2023

The error will gone if you move methods option before data option like below.

TS Playground link with relevant code

defineComponent({
 methods: {
    foo(): number {
      return 1
    }
  },
  data() {
    return {
      data1: this.foo(),
    }
  },
})

It's due to the infer order of typescript.
This limitation still exists in Vue3, but the rest key of data context is inferred to Function in Vue3.

Releated to microsoft/TypeScript#52849

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

No branches or pull requests

5 participants