[英]Property does not exist on type But property exist
我不明白为什么 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”。
打字稿无法从您的使用中推断出action: ChatActionTypes
是DeleteMessageAction
,因为您已将其指定为ChatActionTypes
。 因此,Typescript 会警告您,它无法在ChatActionTypes
的 3 个可能匹配项中的 2 个中找到它。
如果您首先验证action
参数上的type
, 打字稿将能够推断出该操作当时是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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.