TypeScript 2.4 Generic Inference 导致编译错误

TypeScript 2.4 Generic Inference causing compilation errors

我看到现有的 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'.
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 的值并不接受所有类型的操作,因此您会收到错误消息。

没有理由使第二个参数通用,因为您没有在两个 parameters/return 值之间创建约束。就这样

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