typescript - 使用对象扩展时类型不兼容
问题描述
我在打字稿中遇到了一个奇怪的错误,我在互联网上找不到。
type IDialogTypeProps = 'info' | 'alert' | 'success' | 'warning';
interface IDialogProps {
text: string;
type: IDialogTypeProps;
}
const obj = {type: 'warning'}
const dialog:IDialogProps = {
text: 'string',
...obj,
}
打字稿通过警告
Types of property 'type' are incompatible. Type 'string' is not assignable to type 'IDialogTypeProps'
但是,如果我将type: string直接放在对话框对象中,打字稿将在没有警告的情况下编译。我相信这是一个很容易解决的问题。
解决方案
问题是您的obj
对象在没有明确类型的情况下被 Typescript 假定为:
const obj: {
type: string;
}
您可以通过将字符串表示为来强制 TS 不自动将推断类型从 扩大'warning'
到。将 的定义更改为:string
'warning'
const
obj
const obj = { type: 'warning' as const }
推荐阅读
- unity3d - 如何将对象从世界画布动画到覆盖画布
- node.js - 如何在 pug 脚本中访问 bashrc 环境变量。部分
- c++ - clang 不会默认构造 const 类成员
- java - 为什么我需要一个 Rest 控制器?
- html - Wordpress 使整个博客文章可点击
- ios - 为什么我的故事板不能正常工作?
- java - 如何使 SpringBoot/Hibernate 创建单元测试模式?
- python - 如何从 Twitter 打印推文?
- angularjs - Angular 1.x 图像上传预览代码不更新 DOM
- random - OpenCL 内核上的 drand48