Skip to content

generic parameter with default inferred too strictly since 2.7 #21553

@aomarks

Description

@aomarks

TypeScript Version: 2.8.0-dev.20180201

Search Terms: generic parameter default infer keyof 2.7

Code

interface X {
  a: string;
  b: string;
}

function foo<T = X>(x: keyof T, y: keyof T) { }

foo<X>('a', 'b');  // compiles cleanly
foo('a', 'b');  // error TS2345: Argument of type '"b"' is not assignable to parameter of type '"a"'.

Expected behavior:
Both calls to foo() compile with no errors.

Actual behavior:
In the second call, when the generic parameter T is not set explicitly, an error occurs: error TS2345: Argument of type '"b"' is not assignable to parameter of type '"a"'.

It seems that since 2.7, the generic parameter is tightly inferred from the first parameter to be something like {a: string}, so the default (which would have been compatible with both parameters) is not used.

This error does not occur in version 2.6.2. It does occur in version 2.7.1 and 2.8.0-dev.20180201.

Playground Link: https://www.typescriptlang.org/play/#src=%0Ainterface%20X%20%7B%0A%20%20a%3A%20string%3B%0A%20%20b%3A%20string%3B%0A%7D%0A%0Afunction%20foo%3CT%20%3D%20X%3E(x%3A%20keyof%20T%2C%20y%3A%20keyof%20T)%20%7B%20%7D%0A%0Afoo%3CX%3E('a'%2C%20'b')%3B%0Afoo('a'%2C%20'b')%3B

Related Issues:

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions