Vue & TypeScript中动态组件的类型校验实现方法
Vue动态组件的类型检查实现方案
1. 导入Vue组件类型
先从Vue中导入官方提供的Component类型,用来约束pages对象内的组件类型:
import type { Component } from 'vue';
2. 定义合法页面键的联合类型
明确state.page允许的取值范围,避免出现不存在的页面键:
type PageKey = 'Intro' | 'Play' | 'End';
3. 严格约束pages对象类型
替换原来的any接口,用Record工具类型或自定义接口,确保键是PageKey成员,值是标准Vue组件:
// 方式1:用Record工具类型快速定义 const pages: Record<PageKey, Component> = { Intro, Play, End, }; // 方式2:自定义接口(效果一致) interface PageMap { [key in PageKey]: Component; } const pages: PageMap = { Intro, Play, End, };
4. 约束state的page字段类型
确保state.page只能取PageKey内的值,这样模板里pages[state.page]不会出现找不到键的类型错误:
// 以reactive定义的state为例 const state = reactive({ page: 'Intro' as PageKey, });
完整代码示例
<script setup lang="ts"> import type { Component } from 'vue'; import Intro from './Intro.vue'; import Play from './Play.vue'; import End from './End.vue'; import { reactive } from 'vue'; type PageKey = 'Intro' | 'Play' | 'End'; const pages: Record<PageKey, Component> = { Intro, Play, End, }; const state = reactive({ page: 'Intro' as PageKey, }); </script> <template> <component :is="pages[state.page]" /> </template>
改造后TypeScript会自动完成以下检查:
- 禁止给pages添加
PageKey以外的键 - 禁止给pages的键赋值非Vue组件内容
- 禁止给
state.page设置PageKey以外的值 - 模板中的动态组件会被正确识别为合法Vue组件,无类型警告
内容的提问来源于stack exchange,提问作者Kelvin Zhao
相关产品推荐
相关产品推荐

