[Vue3] 关于vue3+ts中使用props进行 interface 类型限制设置默认值报错问题(props: Readonly<Props>))

在这里插入图片描述
在使用 withDefaults 时,为自定义类声明默认值时报错。

报错信息:

Type '{}' is not assignable to type '(props: Readonly<Props>) => object'. Type '{}' provides no match for the signature '(props: Readonly<Props>): object'.

报错时的代码:

//props
interface Props {
  mydata:object,
}
const props = withDefaults(defineProps<Props>(), {
  mydata:{}
});

解决后的代码:

//props
interface Props {
  mydata: object;
}
const props = withDefaults(defineProps<Props>(), {
  mydata: () => {
    return {};
  },
});

我的示例:

在这里插入图片描述

vue官方代码地址:https://cn.vuejs.org/guide/typescript/composition-api.html#typing-component-props

### 使用 `defineProps` 在 TypeScript 中的定义与用法 在 Vue 3 的 `<script setup>` 语法糖中,`defineProps` 是一个编译器宏,用于声明组件接收的属性 (props) 并为其提供类型安全的支持。以下是关于如何在 TypeScript 中使用 `defineProps` 及其类型定义的具体说明。 #### 1. **基于接口的类型声明** 通过定义一个接口来描述 props 的结构,并将其传递给泛型形式的 `defineProps<T>()` 方法。这种方式提供了更清晰的类型提示和更强的静态检查能力[^4]。 ```typescript <script setup lang="ts"> // 定义 Props 接口 interface Props { title: string; count: number; } // 使用 defineProps 泛型方法指定类型 const props = defineProps<Props>(); </script> ``` 上述代码片段展示了如何利用接口定义复杂的 prop 类型并绑定到 `defineProps` 上。 --- #### 2. **嵌套对象与默认值设置** 当需要处理更加复杂的嵌套数据结构时,可以结合 `withDefaults` 来为某些字段设定默认值。下面是一个例子: ```typescript <script setup lang="ts"> import { withDefaults } from &#39;vue&#39;; // 复杂类型interface interface ComplexProps { config?: { active: boolean; timeout: number; }; theme: string; } // 设置默认值 const props = withDefaults(defineProps<ComplexProps>(), { config: () => ({ active: false, timeout: 5000, }), theme: &#39;default&#39;, }); </script> ``` 这里演示了如何为可选参数 (`config`) 和字符串类型 (`theme`) 提供合理的默认值。 --- #### 3. **从外部文件导入 Props 类型** 如果希望将 Props 的定义集中管理,则可以从其他模块导出这些类型,并在当前组件中引入它们。这种方法特别适合大型项目或共享逻辑场景下的维护需求[^3]。 ```typescript // ./types/props.d.ts 文件内容 export interface SharedProps { id: number; name: string; } // 组件内部实现 <script setup lang="ts"> import type { SharedProps } from &#39;./types/props&#39;; const props = defineProps<SharedProps>(); </script> ``` 此模式不仅提高了代码复用率,还减少了重复劳动带来的错误风险。 --- #### 4. **运行时 vs 静态类型声明对比** 需要注意的是,在实际开发过程中可以选择不同的风格来进行 prop 定义。例如 Element Plus 更倾向于采用传统运行时验证机制而非完全依赖 TS 编译期保障[^2]。然而对于现代前端工程而言,推荐优先考虑基于 TypeScript 的强类型解决方案以获得更好的开发体验以及减少潜在 bug 出现的可能性[^1]。 --- #### 总结 综上所述,`defineProps` 结合 TypeScript 能够显著增强 Vue 应用程序的安全性和可读性。无论是简单还是复杂的数据模型都可以轻松应对;同时借助第三方库或者自定义工具进一步扩展功能边界也是可行之策。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值