ts从单独的ts文件中导出interface
// utils.ts export interface Configs { command: string output: string } export interface Device { id: number device_type: string device_ip: string device_address: string device_backup_time: string device_brand: string device_hostname: string device_serial_number: string device_configs?: Configs[] } export class IDevice implements Device { //定义 interface Device 的默认实现类,用于设置默认值 id: number = 1 device_type: string = '' device_ip: string = '' device_address: string = '' device_backup_time: string = '' device_brand: string = '' device_hostname: string = '' device_serial_number: string = '' device_configs?: Configs[] }
在其他.vue文件中导入interface
// detail.vue import { ref, reactive } from 'vue' import { IDevice, Device } from './utils' // 正确用法 const d = reactive<Device>(new IDevice()) d.device_address = 'xxxxxxxxxx' // 但是以下用法vue3还不支持,已经提issue,期待解决 // defineProps不支持使用外部导入的类型,会报错: // Internal server error: [@vue/compiler-sfc] type argument passed to defineProps() must be a literal type, or a reference to an // interface or literal type. const s = withDefaults(defineProps<Device>(), { device_address: 'ddddddddd', })
解决办法:
在ts中我们还可以直接通过类型声明定义props或emits,直接在defineProps方法泛型传入类型就声明,defineEmits也是同理,下面用项目中的一个例子 <script setup> const props = defineProps<{ handle: "add" | "update" parentId: number | null flag: boolean isDir: boolean }>() </script> 或者 如果props需要使用默认值就得用withDefaultsapi,下面是官方的例子 interface Props { msg?: string labels?: string[] } const props = withDefaults(defineProps<Props>(), { msg: 'hello', labels: () => ['one', 'two'] })
参考链接:https://juejin.cn/post/7015587671019880478
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性