使用 TypeScript 在 Vue.js 3 中输入的道具

chi*_*dit 14 typescript vue.js vuejs3 vue-composition-api vuex4

我正在尝试使用组合 API 在 Vue 3 组件中输入提示我的道具。

所以,我这样做:

<script lang="ts">
import FlashInterface from '@/interfaces/FlashInterface';
import { ref } from 'vue';
import { useStore } from 'vuex';

export default {
    props: {
        message: {
            type: FlashInterface,
            required: true
        }
    },
    setup(props): Record<string, unknown> {
            // Stuff
        }
};
Run Code Online (Sandbox Code Playgroud)

我的FlashInterface看起来像这样:

export default interface FlashInterface {
    level: string,
    message: string,
    id?: string
}
Run Code Online (Sandbox Code Playgroud)

除了在这种情况下我收到此错误外,此界面运行良好:

ERROR in src/components/Flash.vue:20:10
TS2693: 'FlashInterface' only refers to a type, but is being used as a value here.
    18 |    props: {
    19 |        message: {
  > 20 |            type: FlashInterface,
       |                  ^^^^^^^^^^^^^^
    21 |            required: true
    22 |        }
    23 |    },
Run Code Online (Sandbox Code Playgroud)

我不明白为什么打字稿认为这是一个值。

我错过了什么?

Bou*_*him 23

您应该将它与PropType从 vue 导入的一起使用,例如Object as PropType<FlashInterface>

import FlashInterface from '@/interfaces/FlashInterface';
import { ref,PropType, defineComponent } from 'vue';
import { useStore } from 'vuex';

export default defineComponent({
    props: {
        message: {
            type: Object as PropType<FlashInterface>,
            required: true
        }
    },
    setup(props) {
            // Stuff
        }
});

Run Code Online (Sandbox Code Playgroud)

注意:您应该使用创建组件defineComponent以获得类型推断。

  • “ Object as PropType&lt;FlashInterface&gt;” 对我来说似乎是一个糟糕的语法,但是嘿,它可以工作,并且为 props 使用 TypeScripts 类型有时非常重要,谢谢 (2认同)
  • @FarhodNematov 它应该是`类型:Array as PropType &lt;FlashInterface []&gt;,`或`类型:Array as PropType &lt;Array &lt;FlashInterface &gt;&gt;,` (2认同)
  • 根据官方文档,使用从另一个文件导入的接口不会使类型检查起作用。https://vuejs.org/guide/typescript/composition-api.html#typing-component-props (2认同)

小智 5

两班轮

<script setup lang="ts">
import FlashInterface from '@/interfaces/FlashInterface';
defineProps<{flash: FlashInterface;}>();
</script>
Run Code Online (Sandbox Code Playgroud)