Reputation: 4020
A subclassed Vue component can be initiated like:
let app = new MyApp({
el: '#app',
data: {
message: 'Hello Vue!',
seconds: 0
},
created() {
setInterval(() => {
this.econds = 'asd';
}, 1000);
}
});
The problem is, neither Flow nor TypeScript will notice the typo or the wrong type on line this.econds = 'asd';
. Is there a way to remedy this? Maybe with class-based components library? But then compilation is a needed build step?
Upvotes: 1
Views: 4112
Reputation: 620
So, if you're using Typescript you can define the type in the variable using class-based components. But that type-check only occurr on the transpilation step. The transpiler will still work will generate the Javascript files, which won't type-check the variable.
Another approach would be type-check manually using typeof(variable) === "number"
. That expression will return true or false, depending on the value of variable
.
Approach 1
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
@Component({
name: 'Home',
})
export default class extends Vue {
message: string = "Hello, Vue";
seconds: number = 0;
created() {
setInterval(() => {
this.seconds = 'asd'; // The transpiler will show an error.
}, 1000);
},
}
</script>
Approach 2
<script>
import Vue from 'vue';
export default Vue.extend({
name: 'Home',
data: function() {
return {
message: 'Hello Vue!',
seconds: 0,
};
},
created() {
setInterval(() => {
let variable = 'asd'
if (typeof(variable) === "number")
this.seconds = variable;
}, 1000);
},
});
</script>
Upvotes: 1
Reputation: 953
I think you should configure your IDE for this properly.
I am using VSCode and the VSCode Extension Vetur https://github.com/vuejs/vetur
<script lang="ts">
import Vue from 'vue';
export default Vue.extend({
name: 'Home',
data: function() {
return {
message: 'Hello Vue!',
seconds: 0,
};
},
created() {
setInterval(() => {
this.econds = 'asd';
}, 1000);
},
});
</script>
In combination with <script lang="ts">
Vetur tells you for this.econds
that this does not exist and displays the message:
Property 'econds' does not exist on type 'CombinedVueInstance<Vue, { message: string; seconds: number; }, unknown, unknown, Readonly<Record<never, any>>>'. Did you mean 'seconds'?Vetur(2551)
No compile step needed, it is on the fly.
Is this what you need?
Upvotes: 1