vue3 typescript如何export引入的interface
引入接口后,不能原封不动地直接export出去。
typescript支持面向对象语言中常见的接口(interface)、类(class)等。
但我近几天发现,一个interface,通过import引入后,如果直接再export出去,是不行的。
语法没有错,但运行时似乎出问题。
比如,我写一个组件timeline,文件结构如下图所示。
为规范其他模块调用,我在_type.ts中定义了一个接口,是关于数据类型的。

按照组件编写的套路,是在组件根目录下有一个index.ts,里面集成各种类型、部件,方便外部引用:
1、index.ts
import timeline from './_timeline.vue'
import { ecolor, iactivityitem as iactivityitembase } from './_type'
export { timeline, ecolor }
export type iactivityitem = iactivityitembase
2、_type.ts
export enum ecolor {
blue = '#427df9',
green = '#34a27f',
red = '#c73641',
gray = '#e4e7ed'
}
export interface iactivityitem {
title: string
time: string
done: boolean
color?: string
}
3、如何将接口iactivityitem传导出去?
在index.ts集成iactivityitem,就是想将它传导出去的。
但是,如前所述,iactivityitem并没有直接定义在index.ts,而是在_type.ts中定义。
之所以这样做,是因为组件的核心部件_timeline.ts也要用到它,由于index.ts有导入_timeline.ts,如果接口定义在index.ts,那么_timeline.ts势必要引用index.ts,这样就出现一个循环。
我也不知道会不会有问题,但想想都不靠谱。
测试过程中,发现在index.ts中引入iactivityitem,然后又export出去,系统会卡住,不知道哪里出了问题:
import { ecolor, iactivityitem } from './_type'
export { ecolor,iactivityitem }枚举ecolor这样做没有问题,接口iactivityitem就有问题,不知道什么原因。
最后的解决办法是继承一下,再export出去:
import { ecolor, iactivityitem as iactivityitembase } from './_type'
export { ecolor }
export type iactivityitem = iactivityitembase
vue3使用interface定义props
//此处注引入
import {proptype} from 'vue'
interface cells{
col:string,
row:string,
field:any
}
interface subform {
cells:array<cells>
}
//定义
const props = {
subform:{
type:object as proptype<sumbform>,
default:{}
},
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论