如果return语句在switch语句之外,则错误地推断出函数的返回类型

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

给定

const ACTION_1 = "ACTION_1";
type ACTION_1 = "ACTION_1";

const ACTION_2 = "ACTION_2";
type ACTION_2 = "ACTION_2";

type ActionTypes = 
  | ACTION_1
  | ACTION_2

export type Reducer<S = any> = (
  state: S | undefined,
  action: ActionTypes
) => S

当我有此减速器时:

const reducer: Reducer<boolean> = (
  state = false,
  action
) => {
  switch (action) {
    case ACTION_1:
       return true;
    case ACTION_2:
       return false;
    default:
  }
  return state;
}

在严格模式下它抱怨此函数的返回类型为IState | undefined,但是当我在switch语句中将return state;换成default: return state时,这很好。甚至只是一个空的default:并将return语句留在底部将使编译器满意。

使用return类型,它甚至可以在vscode中识别出return语句不可访问。我知道它必须考虑到它,因为在运行时它不知道switch语句是否真正详尽。

但是即使我具有默认值,它也确实知道返回绝对不可到达,并且仍然抱怨此函数可能返回IState | undefined

甚至是错误的,因为state参数有一个默认值。因此,它永远不会是不确定的。

这是一个错误吗?还是已知限制?

Playground Link

typescript
1个回答
0
投票

此问题在打字稿版本3.8中已修复。

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