typescript - 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 定义为返回值
VS。
如果 Reducer Type 包含 S 的返回值,为什么不再对返回值进行类型检查?
任何光流和智慧都非常受欢迎。提前致谢。
解决方案
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 支持精确类型之前,它们都不是理想的(精确类型存在一个未解决的问题)讨论了您的确切用例 w/redux 和一些解决方法)。
推荐阅读
- python - 用 pandas 数据框覆盖 Excel 工作表而不影响其他工作表
- amazon-web-services - dynamodb 低网核 3.1
- python-3.x - 有没有办法在 django 模板中迭代列表中的列表?
- python - Linux 上使用 Python3 获取单独应用程序的图像数据
- flutter - Flutter Timer with Hrs, Mins, Sec - Source
- javascript - 反应状态重置
- r - 使用 nanor 的多个变量的 recode_shadow
- r - 如何在R中合并两个大小相同的矩阵?
- java - 无法在jsp文件中传递值
- node.js - Docker 构建显示无效的 containerPort