首页 > 解决方案 > Redux 的 Reducer<> 类型没有正确地将返回类型传递给 reducer?

问题描述

信息: 在 Jetbrains Rider 中使用 Typescript 3.3.3333

鉴于这种类型的定义Reducer<State, Action>

* @template S The type of state consumed and produced by this reducer.
* @template A The type of actions the reducer can potentially respond to.
*/
export type Reducer<S = any, A extends Action = AnyAction> = (
  state: S | undefined,
  action: A
) => S

为什么S非类型的返回类型会检查我从减速器返回的状态,除非我明确定义它?

export const INITIAL_STATE: AuthenticationState = {
    authenticationInProgress: false,
    accessToken: null,
    tokenType: null,
    expiryTimeMs: null,
    errorInformation: null,
    isAdmin: false,
};

export const authenticationReducer: Reducer<AuthenticationState, 
    AuthenticationActions> = (state = INITIAL_STATE, action): 
(why is this necessary??) ->  AuthenticationState => {
        switch (action.type) {
            case "authentication/user_authentication_request": {
                return {
                    ...state,
    problem -> hello: "hi",
                    authenticationInProgress: true,
                };
            }
...

我期望的行为,无需将 AuthenticationState 定义为返回值 我期望的行为,无需将 AuthenticationState 定义为返回值

VS。

如果 Reducer Type 包含 S 的返回值,为什么不再对返回值进行类型检查? 为什么没有更多类型检查返回值是Reducer<S, A> 类型包含S的返回值

任何光流和智慧都非常受欢迎。提前致谢。

标签: typescriptredux

解决方案


TLDR:这是 TypeScript 中的预期行为,因为过多的属性检查是如何工作的。

在您的情况下,您定义的箭头函数具有具有多余(或额外)属性的返回类型。对于 TypeScript,这完全没问题。

在一个简化的例子中,看看这个行为:

type a = () => { a: string };
type b = () => { a: string, b: string };

declare let myA: a;
declare let myB: b;

myA = myB; // OK! (excess properties are not checked)
myB = myA; // Error: missing required property 'b'

问题的症结在于,您实际上是在分配myBmyA并期待一个错误,但在分配myAmyB.

您有几个选项可以使您的代码按预期工作(例如您提出的那个,您明确定义返回类型),但在 TypeScript 支持精确类型之前,它们都不是理想的(精确类型存在一个未解决的问题)讨论了您的确切用例 w/redux 和一些解决方法)。


推荐阅读