Typescript: normal function type and array function type behave differently with tuple type in function parameters

Created on 17 Jul 2019  路  3Comments  路  Source: microsoft/TypeScript


TypeScript Version: 3.5.2

Code

function test1 (a: {
    f (n: any[]): void;
}) {}
function test2 (a: {
    f: (n: any[]) => void;
}) {}


test1({
    f ([s]: [string]) {}
});

test2({
    f ([s]: [string]) {}
});

Expected behavior:
Type check for test1 and test2 should have same result: both of them should pass type check, or neither of them pass type check

Actual behavior:
test1 passed type check, test2 didn't:

Type '([s]: [string]) => void' is not assignable to type '(n: any[]) => void'.
  Types of parameters '__0' and 'n' are incompatible.
    Property '0' is missing in type 'any[]' but required in type '[string]'.

Playground Link:
https://www.typescriptlang.org/play/index.html?experimentalDecorators=true&emitDecoratorMetadata=true#code/GYVwdgxgLglg9mABFApgZygRkQCgIYBciA3gFCIWLC5hF5gCeA2gLoCURAbnDACYDcpAL5sSQ0qEiwEydFABMuQiXKVgRHLUT1m7RAF4AfIm59BIsaSuoMmHGUpVcTNCyIuoAJxhgA5nuJxEUFSGwV7VQpqHBc3RA9vPwCgtn4gA

Working as Intended

Most helpful comment

When the JavaScript ecosystem isn't full of unsound class hierarchies (e.g. the DOM!)

All 3 comments

I agree it's confusing but this is working as intended (as I understand it).

The type { f(n: any[]): void; } represents an object with a method named f, while the type { f: (n: any[]) => void; } represents an object with a function-valued property named f. Those are very similar, but not the same.

Specifically, with the --strictFunctionTypes compiler option enabled, parameters of functions are checked contravariantly, while parameters of methods are still checked bivariantly.

Since [string] is assignable to any[] but any[] is not assignable to [string], your test1 call passes the bivariant check but your test2 call fails the contravariant check.

--strictMethodTypes when?

When the JavaScript ecosystem isn't full of unsound class hierarchies (e.g. the DOM!)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jbondc picture jbondc  路  3Comments

kyasbal-1994 picture kyasbal-1994  路  3Comments

manekinekko picture manekinekko  路  3Comments

weswigham picture weswigham  路  3Comments

Antony-Jones picture Antony-Jones  路  3Comments