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

 

posted @   明天OoO你好  阅读(5114)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
点击右上角即可分享
微信分享提示