3

I'm getting an issue that only seems to be a problem with my compiler. It doesn't like that it can't find properties I've defined in the data section. If I replace 'this' with '(this as any)' it runs just fine. That leads me to believe that I have an issue with typescript that I need to fix. The error message is very specific to my situation but I'm not sure how to fix it.

enter image description here

EDIT to add shims-vue.d.ts

declare module '*.vue' {
  import Vue from 'vue';
  export default Vue;
}
4
  • It looks like TypeScript does not know how it should handle Vue files. The this in your error refers to the computed object and not to the component. How do you compile your code? Commented Jul 16, 2020 at 20:13
  • I use, "vue-cli-service serve" to build and host the code. I think it uses webpack... but I'm not sure honestly. Commented Jul 16, 2020 at 20:18
  • Do you have a vue-shims.d.ts in your project? Also your lines 67 to 69 look funky because you say (this as any).. Generally you don't need to say any at all because this. is perfectly fine. The use of any pretty much defeats a core purpose of using TS in the first place Commented Jul 17, 2020 at 12:07
  • (this as any) is my work around for the issue I'm asking about. It allows the code to be compiled and it works fine at runtime. If I replaced the this that the compliler is complaining about with (this as any) it would compile and work just fine. I just agree with you that it looks funky and I don't like doing it. I'd love to figure this issue out and remove them all. Edited my question to include the vue-shims.d.ts file I'm using. Not sure what it does though. Commented Jul 18, 2020 at 15:47

2 Answers 2

1

It appears computed properties may require explicit type annotations, as in this answer. Instead of

items() {
...
}

you'd have

items(): ItemType[] {
...
}

Typescript should then understand the this reference. It's also worth considering the class component syntax, which in my experience is better suited for typescript in Vue 2 (this issue wouldn't happen).

Sign up to request clarification or add additional context in comments.

Comments

1

What ended up fixing this was my declarative statement. My error:

export default {
    name: 'Home',
    components: {
        ...
    },
    ...
};

The fix:

export default Vue.extend({
    name: 'Home',
    components: {
        ...
    },
    ...
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.