当我将 switch 语句案例移动到自己的函数时出现 TypeScript 错误?

标签 typescript redux

我正在将 TypeScript 与 Redux 结合使用。此代码运行良好:

export type action =
  | {
      type: "do-other-thing";
      name: string;
    }
  | {
      type: "do-something";
      index: number;
    };

function reducer(state: state = initState, action: action): state {
  switch (action.type) {
    case "do-something":
        if (action.index === 0) return state;
        // More logic
    case "do-other-thing":
        // More logic
    default:
        return state;
  }

但是我想将 switch 语句中的返回情况移至它们自己的函数中:

function doSomething(state: state, action : action): state {
    if (action.index === 0) return state;
    // more logic
}

function reducer(state: state = initState, action: action): state {
  switch (action.type) {
    case "do-something":
        return doSomething(state, action);
    case "do-other-thing":
        // More logic
    default:
        return state;
  }

现在 doSomething 函数出现 TypeScript 错误:

Property 'index' does not exist on type 'action'. Property 'index' does not exist on type '{ type: "do-something"; width: number; isLandscape: boolean; }'.ts(2339)

我可以看到 TypeScript 不知道由于 switch 语句,action 对象将具有 index 属性。有没有办法让它意识到这一点?

最佳答案

因为您在 doSomething 函数上将参数定义为 action,所以任何人都可以在其他地方传递任何 action。您很可能希望将其实际定义为更受限制的类型,如下所示:

type DoOtherThingAction = { type: "do-other-thing"; name: string; };
type DoSomeThingAction = { type: "do-something"; index: number; };
export type action = 
  | DoOtherThingAction
  | DoSomeThingAction;

然后:

function doSomething(state: state, action : DoSomeThingAction): state {
    if (action.index === 0) return state;
    // more logic
}

关于当我将 switch 语句案例移动到自己的函数时出现 TypeScript 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60602811/

相关文章:

javascript - Scala.js 可以生成 TypeScript d.ts 类型绑定(bind)吗?

javascript - 如何使用 jest 测试 void 函数

angular - 强制 Angular 遵循 json 中的接口(interface)类型

javascript - 为 React Component Props 解构 ImmutableJS Map

javascript - 从 Redux Store 更新后,React Component 无法重新呈现

javascript - 将中间件应用于单个商店

typescript - 如何启用 async.mapLimit 与 TypeScript async/await 配合使用

dictionary - Typescript:使用 Object.keys 迭代字典

redux - Flutter Redux Navigator GlobalKey.currentState 返回 null

reactjs - 在 useEffect() 内部使用 useDispatch() 时,操作似乎不会立即调用