Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript not inferring rest parameters correctly

There is a function bar of type Bar. Modified version of the function (barStochastic) is supposed to reset the pseudo-random generator before calling, the bar, but apart from that, it is identical.

Since Bar has many arguments, I want to pass them using ...args spread syntax.

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);
};

My editor does not complain about this (it is usually consistent with TS compiler), but compilation fails.

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);
                  ~~~~~~~~~~~~~~~~~~~~~~~~~

I would expect ...args to be inferred as [number, number, number]. That would solve both errors.

Is this a bug or intended behavior?


Setup:

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",
  }
}
like image 441
Jaroslav Šmolík Avatar asked Oct 14 '25 09:10

Jaroslav Šmolík


1 Answers

You are using Typescript 2.9. The feature you are trying to use is Tuples in rest parameters and spread expressions which was implemented in 3.0.

You can try your example in the playground and it will work as expected.

Since your editor does not complain, my guess is your editor is using 3.0 (VS Code 1.27.1 comes with the 3.0 language service) but you compile using 2.9.

like image 115
Titian Cernicova-Dragomir Avatar answered Oct 17 '25 16:10

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!