Typescript: Extract array-parameter has wrong type error catching

Created on 8 Aug 2018  路  4Comments  路  Source: microsoft/TypeScript


TypeScript Version: 3.1.0-dev.201xxxxx


Search Terms:
Array spread types
Spread args array
spread generic types

Code
function call was found on msdn blog
I tried to call it with wrong arguments and get an error, but found a case that is not treated as an error, but it should.

function call<TS extends any[], R>(fn: (...args: TS) => R, ...args: TS): R {
    return fn(...args);
}

function test(a: number[]) {
}

call(test, [1, 2]); // this is ok
call(test, ["foo", "bar"]); // this has type error and is ok
call(test, ["foo", 1]); // this is treated as valid but is not

Expected behavior:
Both 2nd and 3rd calls should cause error

Actual behavior:
Only 2nd call is wrong, adding at least one number to array of strings makes this legit arg for function call

Playground Link:
Demo

Question

Most helpful comment

Unfortunately this is a case of parameter bivariance - you'll need to enable strictFunctionTypes to correctly have the error flagged

All 4 comments

I have expirienced same problem with this code:

function call<TS extends any[], R>(fn: (...args: TS) => R, ...args: TS): R {
    return fn(...args);
}

interface IFoo{
    bar: number;
}

function test(a: IFoo[]) {
}

call(test, [1, 2]);
call(test, [{ bar: 4 }]);
call(test, ["baz", { bar: 4 }]);
call(test, [ { bar: 4 }, 44, true, "dddd"]);

so, it isn't emmit error if at least one element in array is correct

--strictFunctionTypes ?

Unfortunately this is a case of parameter bivariance - you'll need to enable strictFunctionTypes to correctly have the error flagged

Thanks @RyanCavanaugh, @AnyhowStep. It helped

Was this page helpful?
0 / 5 - 0 ratings

Related issues

siddjain picture siddjain  路  3Comments

bgrieder picture bgrieder  路  3Comments

seanzer picture seanzer  路  3Comments

Roam-Cooper picture Roam-Cooper  路  3Comments

kyasbal-1994 picture kyasbal-1994  路  3Comments