Live2d Test Env

vue3中关于指定props的复杂ts类型

如果要对props的数据进行指定类型, 基本类型可以直接使用类型约束,复杂类型可以使用PropType进行约束

interface ItemInterface {
title: string
code: string
status: number
icon: string
}
const props = defineProps({
type: String,
userId: String,
currentItem: {
type: Object as PropType<ItemInterface>, // 使用 PropType 指定类型
default: () => ({})
}
})

来自gpt的解释:
解析说明:

  1. ItemInterface 接口: 定义了 currentItem 属性期望的对象结构,包括 title, code, status, icon 四个字段,每个字段的类型都是 string 或 number。

  2. currentItem 的定义:

使用 PropType 明确告诉 TypeScript,currentItem 应该是 ItemInterface 类型的对象。
Object as PropType 是一个类型断言,用来强制指定 currentItem 的类型为 ItemInterface。

  1. 默认值:

default: () => ({}) 指定 currentItem 的默认值为空对象,这符合 Vue 3 中 props 的默认值设定方式。

为什么这样做是好的选择?
  1. 类型安全: 使用 PropType 可以确保在组件使用 currentItem 属性时,只接受符合 ItemInterface 接口定义的对象。

  2. 清晰明了: 在 Vue 3 组件中,使用 PropType 显式指定 props 的类型,使得组件的使用者和维护者能够清晰地了解每个 prop 的预期类型和结构。

  3. 可读性: 增强了代码的可读性和可维护性,特别是在较大的项目中,能够帮助团队成员更快速地理解和使用组件。

以上。

posted @   致爱丽丝  阅读(695)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示