场景:封装一个组件,需要导出它的类型,作为一个全局类型去使用
import type { ColumnProps } from '@/components/global/m-table/index.d.ts';
import type { VNode, h } from 'vue';
declare namespace $component {
// interface column extends ColumnProps {}
export type column = ColumnProps;
export type h = h;
}
命名为table.d.ts,放在全局声明文件里面。发现无法生效,全局无法使用。
解决方法
如果import引入,会被认为是一个本地模块,而不是全局模块,使用import()语法可以解决
// import type { ColumnProps } from '@/components/global/m-table/index.d.ts';
// import type { VNode, h } from 'vue';
// 如果import引入,会被认为是一个本地模块,而不是全局模块,使用import()语法可以解决
declare namespace $component {
export type column =
import('@/components/global/m-table/index.d.ts').ColumnProps;
export type h = typeof import('vue').h;
}
最终结果:
总结
TS有两种模块类型声明,本地模块和全局模块,第二种允许写入合并已经存在模块声明的全局模块声明中,d.ts文件作为一个全局模块声明只有你没有import关键字。如果你用了import会作为一个本地模块而不是全局模块,所以才会导致全局声明没有生效。使用import()语法可以解决。
案例项目地址:github.com/WangZhenHao…