打字稿错误,该属性应不存在

时间:2019-10-27 20:10:41

标签: typescript

我不明白此消息是怎么发生的。

Property 'message' does not exist on type '{ username: string; } | { message: string; }'.

相关代码(已删除):

// types.ts
type LoginMessage = {
  type: 'login';
  payload: { username: string };
};

type SendChatMessage = {
  type: 'send_chat_message';
  payload: { message: string };
};

export type ClientToServerMessage = LoginMessage | SendChatMessage;

// reducer.js

const { message } = action.payload; // this is the line that causes the error
// action has type ClientToServerMessage

2 个答案:

答案 0 :(得分:0)

答案在其他地方...在切换情况下缺少break;

答案 1 :(得分:0)

您需要使用user-defined type guard来缩小ClientToServerMessage联合类型。

文档中的示例说明了如何通过缩小联合类型来使用它们。

function isFish(pet: Fish | Bird): pet is Fish {
    return (pet as Fish).swim !== undefined;
}

如果定义了Fish,则代码的任何条件分支会将类型范围缩小到swim

if (isFish(pet)) {
    pet.swim(); // compiler knows that `pet` is of the `Fish` type
}