javascript - 类型上不存在属性但属性存在
问题描述
我不明白为什么 TypeScript 会抛出错误
interface SendMessageAction {
type: 1;
}
interface DeleteMessageAction {
type: 2;
idBlock:string;
}
type ChatActionTypes = SendMessageAction | DeleteMessageAction;
const CounterReducer = (action:ChatActionTypes) => {
action.idBlock
}
Property 'idBlock' does not exist on type 'ChatActionTypes'.
Property 'idBlock' does not exist on type 'SendMessageAction'.
接口DeleteMessageAction中存在字段 idBlock
如何修复错误?
解决方案
如果您分析给出的错误消息,它会说以下内容:
类型“ChatActionTypes”上不存在属性“idBlock”。
“SendMessageAction”类型上不存在属性“idBlock”。
typescript无法从您的用法中推断出 theaction: ChatActionTypes
是 a DeleteMessageAction
,因为您已将其指定为 a ChatActionTypes
。因此,Typescript 会警告您,它在ChatActionTypes
.
如果您首先验证type
onaction
参数,则打字稿将能够推断出当时的动作是 a DeleteMessageAction
,例如通过执行以下操作:
const CounterReducer = (action:ChatActionTypes) => {
if (action.type === 2) { // 2 is mentioned on DeleteMessageAction for type
action.idBlock; // so you can now do something with idBlock here
}
}
推荐阅读
- linux - MV 命令不适用于以引号开头的文件名
- c# - 为什么 ZedGraph 不绘制第二条曲线?
- php - 带 str_replace 的数字格式
- javascript - (Three.js /Three.js 编辑器)如何制作逼真的汽车转向效果?
- ruby-on-rails - Rails 中格式不正确的异常
- python - 如何替换熊猫数据框中错误标记的日期?
- c# - Visual Studio wcf客户端c#SOAP evenlope方法名称不同大小写
- angular - 我如何解析构造函数的所有参数
- java - Spring boot 是否提供任何用于生成覆盖率报告的内部库
- reactjs - ReactDOM 你好世界