Reducer <>类型的Redux没有正确地将返回类型传递给reducer?

问题描述 投票:1回答:2

信息:在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的返回类型没有类型检查我从reducer返回的状态,除非我明确定义它?

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定义为返回值Behavior I expect without needing to define AuthenticationState as the return value

VS.

如果Reducer Type包含S的返回值,为什么不再对返回值进行类型检查? Why is there no more type checking for the return value is the Reducer<S, A> Type includes the return value of S

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

typescript redux
2个回答
1
投票

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'

问题的关键在于你基本上将myB分配给myA并期待错误,但是在将myA分配给myB时只会出错。

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


0
投票

正如Christian Santos所说,这是预期的行为。

如果您希望获得类型安全的redux体验,那么我建议您查看一些专为此设计的redux扩展!

看看redux-fluent

enter image description here enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.