typescript - 使用 TypeScript 输入 Vue.js 3 的 Prop

标签 typescript vue.js vuex vuejs3 vue-composition-api

我正在尝试使用组合 API 在 Vue 3 组件中输入提示我的 Prop 。
所以,我正在这样做:

<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
    }
};
我的 FlashInterface看起来像这样:
export default interface FlashInterface {
    level: string,
    message: string,
    id?: string
}
此界面运行良好,但在这种情况下我收到此错误:
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 |    },
我不明白为什么 TypeScript 认为这是一个值。
我错过了什么?

最佳答案

您应该将它与 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
        }
});

注:你应该使用 defineComponent 创建你的组件为了得到类型推断。
脚本设置
您可以使用 defineProps 定义 Prop 以两种方式发挥作用:
<script setup lang="ts">
import FlashInterface from '@/interfaces/FlashInterface';
mport { ref,PropType, defineComponent , defineProps} from 'vue';
interface IProps{
   message : FlashInterface
}
const props = defineProps<IProps>()

或者
<script setup lang="ts">
...
const props = defineProps({
        message: {
            type: Object as PropType<FlashInterface>,
            required: true
        }
    })

关于typescript - 使用 TypeScript 输入 Vue.js 3 的 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64831745/

相关文章:

vue.js - Vuex 存储数据总是驻留在内存中?

javascript - vuex 突变取代了整个状态

javascript - 使用 vuex 和 vue router 的实例上未定义属性或方法 "X"

typescript - @Reflect.metadata 生成错误 TS1238 : Unable to resolve signature of class decorator when called as an expression

javascript - 如何优雅地使用 v-model 和 Vuex store?

javascript - 为什么我无法从另一个组件访问 vue.js 属性?

javascript - Array Splice 总是从最后删除一个项目?

typescript promise 拒绝和 vscode 调试器行为

html - PrimeNg 的 <pcalender> 中的日期验证逻辑

node.js - Node 类型脚本应用docker命令错误