如果声明参数类型,TypeScript 函数实现会将参数类型降级为 `any`

标签 typescript

我有一个这样的函数接口(interface):

interface Callback {
  (a: string, b: number): void;
}

而且我可以在不声明参数类型的情况下实现它,如下所示:

const callback: Callback = (a, b) => { }

在这种情况下,TypeScript 理解 callback 的参数类型实际上是 (a: string, b: number)

但是,如果我用一个键入的参数声明它,例如 b: number:

const callback: Callback = (a, b: number) => { }

另一个参数a的类型变为anyExample in the Playground .奇怪的是编译器确实知道 a 应该是什么类型,因为它不会让你错误地定义它,例如 (a: boolean, b: number)会说参数不兼容。为什么它不推断a的参数类型?


上面是一个简单的例子,但在尝试生成类型安全的 Redux reducer map 时让我有些头疼。 :

interface IReducer<TState> {
  (state: TState, action: IAction): TState;
}

interface IReducerMap<TState> {
  [actionType: string]: IReducer<TState>;
}

interface MyState { hello: string; }

interface MyAction extends IAction { say: string; }

const myReducerMap: IReducerMap<MyState> = {
  // Result: `(state: MyState, action: IAction) => MyState`
  // But I get an error on `action.say` not defined in `IAction`
  reducer1: (state, action) => {
    return { hello: action.say };
  },

  // Result: `(state: any, action: MyAction) => computed`
  reducer2: (state, action: MyAction) => {
    return { hello: action.say + state.this_should_be_an_error };
  },

  // Works but relies on you to correctly defining state
  reducer3: (state: MyState, action: MyAction) => {
    return { hello: action.say };
  }
}

由于每个函数将采用 IAction 的子类型作为其 action 参数(在本例中为 MyAction),我必须在中声明其类型回调参数。但是一旦我声明了它的类型,我就失去了 state 的类型,我必须声明它。当我有几十个回调并且每个回调都有一个像 DataImportMappingState 这样的真实状态名称时,这很烦人。

最佳答案

ab 的推断来自上下文打字。以前,只有在所有 参数都没有注释的情况下,参数才会根据上下文进行类型化。

This behavior has changed in the latest build of the TypeScript compiler因为它似乎不直观。现在上下文类型将应用于所有没有显式类型注释的参数。

关于如果声明参数类型,TypeScript 函数实现会将参数类型降级为 `any`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40350610/

相关文章:

angular - 退订一系列订阅

javascript - 如何在javascript中比较array1的obj和array的obj

javascript - 导入 typescript 时如何在路径中使用变量

javascript - 如何更改 Koa 的非定义路由的 http 状态码

javascript - 如果不存在,如何有效地将元素添加/推送到数组

typescript - ts-node-dev:使用 dotenv 时没有提供要运行的脚本

javascript - IOS平台的nativescript应用程序在iPad上完美运行吗?

typescript - 你能让 TS 从被赋值的值中推断出变量的泛型类型参数吗?

typescript - 无法将Angular 2项目与webpack捆绑在一起

javascript - Typescript 函数类型推断