TypeScript 2.4 Generic Inference导致编译错误

时间:2017-07-25 15:22:35

标签: typescript typescript2.4

由于通用推理的变化,我看到现有的TypeScript代码中断。

示例:

interface Action {
    type: string;
}
interface MyAction extends Action {
    payload: string;
}
interface MyState {}

type Reducer<S> = <A extends Action>(state: S, action: A) => S;

const myReducer: Reducer<MyState> = (state: MyState, action: MyAction) => {
    if (action.type === "MyActionType") {
        return {};
    }
    else {
        return {};
    }
};

编译错误:

Error:(11, 7) TS2322:Type '(state: MyState, action: MyAction) => {}' is not assignable to type 'Reducer<MyState>'.
  Types of parameters 'action' and 'action' are incompatible.
    Type 'A' is not assignable to type 'MyAction'.
      Type 'Action' is not assignable to type 'MyAction'.
        Property 'payload' is missing in type 'Action'.

1 个答案:

答案 0 :(得分:1)

interface MyOtherAction {
    type: 'MyOtherActionType'
    foo: number
}

declare const state: State
declare const myOtherAction: MyOtherAction

// the following is a valid call according to myReducer's signature
myReducer(state, myOtherAction)

但是,您分配给myReducer的值并不接受所有类型的操作,因此您会收到错误。

由于您没有在两个参数/返回值之间创建约束,因此没有理由将第二个参数设为通用。只是做

type Reducer<S> = (state: S, action: Action) => S;