【问题标题】:Typescript not inferring rest parameters correctly打字稿没有正确推断剩余参数
【发布时间】:2019-02-22 03:52:24
【问题描述】:

有一个bar 类型的函数Bar。该函数的修改版本 (barStochastic) 应该在调用 bar 之前重置伪随机生成器,但除此之外,它是相同的。

由于Bar 有很多参数,我想使用...args 扩展语法来传递它们。

const random = {
    initState() {
        return 1;
    },
};
type Bar = (a: number, b: number, c: number) => number;
const barDeterministic: Bar = (a, b, c) => {
    return a + b + c;
};
const barStochastic: Bar = (...args) => {
    random.initState();
    return barDeterministic(...args);
};

我的编辑器没有抱怨这个(通常与TS编译器一致),但是编译失败。

error TS7019: Rest parameter 'args' implicitly has an 'any[]' type.

10     const barStochastic: Bar = (...args) => {
                                   ~~~~~~~


error TS2556: Expected 3 arguments, but got 0 or more.

12         return barDeterministic(...args);
                  ~~~~~~~~~~~~~~~~~~~~~~~~~

我希望...args 被推断为[number, number, number]。 这将解决这两个错误。

这是错误还是预期行为?


设置:

Deepin 15.7 Desktop
Node v10.9.0
tsc 2.9.2
vscode 1.27.1

tsconfig.json:

{
  "include": [
    "./src/**/*"
  ],
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": [
      "es2015"
    ],
    "allowJs": true,
    "sourceMap": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "moduleResolution": "node",
    "baseUrl": "./src",
  }
}

【问题讨论】:

    标签: rest typescript arguments spread-syntax inferred-type


    【解决方案1】:

    您使用的是 Typescript 2.9。您尝试使用的功能是在 3.0 中实现的 Tuples in rest parameters and spread expressions

    您可以在playground 中尝试您的示例,它会按预期工作。

    由于您的编辑器没有抱怨,我猜您的编辑器使用的是 3.0(VS Code 1.27.1 附带 3.0 语言服务)但您使用 2.9 进行编译。

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-01
      • 2020-04-09
      • 1970-01-01
      相关资源
      最近更新 更多