@vue-generic 显式指定组件泛型类型,但是不生效 "vue": "^3.5.21" #14367
Replies: 2 comments
-
|
你这个点基本不在 Vue runtime 本体,而是在 TS/IDE 语言服务(Volar / @vue/language-tools)这条链路上:<script setup generic="..."> 和 都是类型系统/编辑器在解析,不是运行时特性。官方文档里也明确给了 @vue-generic 的用法示例。 下面给你几个最常见的“看起来写对了但不生效”的原因 + 直接可用的修法。
你现在写的是: <!-- @vue-generic {DataSourceType} -->
<ProTable ... />这要求 DataSourceType 在当前 SFC 的 template 类型环境里“可解析”。最不踩坑的写法是照官方示例用 import(): <template>
<!-- @vue-generic {import('@/types').DataSourceType} -->
<ProTable :columns="columns" :request="request" />
</template>官方文档示例就是这种 import('...').Type 形式。 备选方案是:在当前组件的 <script setup> 里显式 import type: <script setup lang="ts">
import type { DataSourceType } from '@/types'
</script>
@vue-generic 主要影响的是:该组件标签上的 props / slots / emits 的类型检查与补全。 <ProTable :columns="columns" />就“反向推导”出 columns 变量应该是什么类型。 所以如果你想让 columns 在你定义它的时候就有 keyof DataSourceType 那种补全,你需要给 columns 自己一个类型上下文,比如 satisfies: import type { ProTableColumnsType } from './tableType'
import type { DataSourceType } from '@/types'
const columns = [
// 在这里写 dataIndex / field 时才会按 DataSourceType 补全
] satisfies ProTableColumnsType<DataSourceType>或者用一个小工厂函数制造上下文: const defineColumns = <T>() => <C extends ProTableColumnsType<T>>(c: C) => c
const columns = defineColumns<DataSourceType>()([
// ...
])
如果你不是直接 import ProTable from './index.vue',而是从 index.ts 里导出(比如 withInstall(ProTable)、Object.assign、插件包装),很容易把组件类型变成普通 DefineComponent,泛型构造签名被抹平,那 @vue-generic 就没法套进去。 解决:在需要泛型的地方直接 import 那个 .vue SFC(你截图里 ProTable 自己是 .vue,父组件也尽量这么引)。
你提到的讨论贴本身就是 Vue org 里的提问(但本质属于语言工具范畴)。 VSCode 扩展:Vue - Official 依赖:vue-tsc / @vue/language-tools / typescript 如果这些还是老版本,就会出现“写了注释但完全没反应”。 一套你可以直接试的“最小修复版” <script setup lang="ts">
import ProTable from './pro-table/index.vue'
import type { DataSourceType } from '@/types'
import type { ProTableColumnsType } from './pro-table/tableType'
const columns = [
// ...
] satisfies ProTableColumnsType<DataSourceType>
</script>
<template>
<!-- @vue-generic {import('@/types').DataSourceType} -->
<ProTable :columns="columns" />
</template>如果你照上面改完: @vue-generic 依然“完全没任何类型效果”(props 不报错、不补全)——那几乎可以断定是 语言工具链没吃到这个指令(版本/IDE/插件冲突)。 但如果 props 的类型检查开始变严格,而你想要的是 columns 里的字段补全——那就是第 2 点:给 columns 自己加 satisfies/工厂函数上下文就行。 |
Beta Was this translation helpful? Give feedback.
-
|
Hi @jianxingli! Working with Vue reactivity system and compilers can sometimes present interesting edge cases. A few quick things to consider regarding this topic:
I highly recommend checking out the Vue DevTools extension to inspect the component tree and verify if the state is updating as expected. Let me know if you want to dig deeper into the specific component logic. Hope this points you in the right direction! Let me know how it goes. Happy coding! |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
自定义组件在 setup中声明泛型


组件在使用的情况
期望在组件使用@vue-generic 声明的类型 能正确推导
Beta Was this translation helpful? Give feedback.
All reactions