[英]How to annotate a variable in Vue as a Vue component when using Typescript?
我正在使用 VueJS 和 Typescript,我沒有使用類樣式的 Vue 組件。
假設我有以下 Vue 組件。
<template>
<my-component ref="component"/>
</template>
<script lang="ts">
import MyComponent from "@/components/my-component.vue";
export default Vue.extend({
components: {
MyComponent,
},
methods: {
async someMethod() {
// How do I annotate the following component variable as type "MyComponent"?
const component = this.$refs["component"];
console.log(component.$props);
},
},
});
</script>
如何正確注釋someMethod
方法中的component
變量,以便 Typescript 編譯器知道$props
等屬性?
以下(這是我最初的直覺)不起作用。
const component: MyComponent = this.$refs["component"];
在 vue+vscode 生態系統中,現在 typescript 無法從模板聲明中推斷類型。 (也許會)
對於 $refs[xxx]:
輸入'Vue | 元素 | Vue[] | Element[]' 不可分配給類型 'Vue'。
您可以改用類型斷言:
const component = this.$refs["component"] as typeof MyComponent;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.