【问题标题】:Interface method argument types ignored by TypeScriptTypeScript 忽略的接口方法参数类型
【发布时间】:2020-06-22 15:10:29
【问题描述】:

令我惊讶的是,以下代码编译时没有错误(tsc 3.9.5):

interface IDateHandler {
  handleDate: (Date) => void;
}

let dateHandler: IDateHandler = {
  handleDate: (d: Date) => {},
};

dateHandler.handleDate([1, 2, 3]);

更令人惊讶的是,如果将 handleDate([1, 2, 3]) 替换为 handleDate([1, 2, 3], 4)tsc 会发出 error TS2554: Expected 1 arguments, but got 2.

所以它清楚地知道handleDate 的函数签名,但由于某种原因它完全忽略了类型本身。

甚至更多令人惊讶的是,省略接口声明使类型检查按预期工作:

let dateHandler = {
  handleDate: (d: Date) => {},
};

dateHandler.handleDate([1, 2, 3]);

// error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'Date'.
//   Type 'number[]' is missing the following properties from type 'Date': toDateString, toTimeString, toLocaleDateString, toLocaleTimeString, and 37 more.

什么给了?

【问题讨论】:

标签: typescript


【解决方案1】:

我注意到的第一件事是代码可能在第 2 行被破坏。handleDate 签名中应该指定了一个参数类型。

它编译的原因是代码本身是有效的。在您的代码中,您有一个名称为 Date未指定类型的参数。

您应该做的是将--strict--noImplicitAny 编译器选项添加到您的 tsc 配置(tsconfig.json 或命令行参数)。完成后,您应该会收到类似的错误

Error:(2, 18) TS7051: Parameter has a name but no type. Did you mean 'arg0: Date'?

见: Typescript Compiler Options

【讨论】:

    【解决方案2】:

    查看@VLAZ的评论后自己发现了问题:

    启用 TypeScript 的默认“隐式任何”行为后,(Date) => void 变为 (Date: any) => void

    将函数类型签名更改为(d: Date) => void 使tsc 报告预期的:error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'Date'.

    【讨论】:

      猜你喜欢
      • 2018-02-04
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      • 2017-09-26
      • 2015-10-08
      • 1970-01-01
      • 2012-04-28
      • 1970-01-01
      相关资源
      最近更新 更多