首页 > 解决方案 > 将 switch 语句案例移动到自己的函数时出现 TypeScript 错误?

问题描述

我将 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 错误:

“操作”类型上不存在属性“索引”。类型 '{ type: "do-something"; 上不存在属性 'index' 宽度:数字;isLandscape:布尔值;}'.ts(2339)

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

标签: typescriptredux

解决方案


函数不适doSomething用于所有动作,但对于具有index属性的动作,我会拆分一些打字,以便能够更清楚地键入需求:

type A = {
      type: "do-other-thing";
      name: string;
    };
type B = {
      type: "do-something";
      index: number;
    };
type Action = A | B

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

现在仅适用于您的类型doSomething的变体。BAction


推荐阅读