Closed
Description
Motivating example (one of many):
function compare<T>(lhs: T, rhs: T): boolean {
return lhs === rhs;
}
if(compare('1', 1)) { // Expected: Error -- I made 'compare' generic for a reason!
/* ... */
}
Proposal
When generic type inference performs its Best Common Type operation (4.12.2), it should be an error if this returns {}
when {}
was not one of the input types.
This is entirely consistent with other behavior already in the compiler:
var foo = bar ? '1' : 1; // Error, no BCT between '1' and 1
function fn() { // Error, no BCT between '1' and 1
if(foo) {
return '1';
} else {
return 1;
}
}
Open Questions
From @KamyarNazeri -- should this apply when there are zero input types? e.g.:
class List<T> {
items: T[];
}
var x = new List(); // Probably want an error here
That seems desirable, but has some collateral damage:
function foo<T>(x: number, a?: T, b?: T) { }
foo(0); // Error, zero input types provided for inference
This would come up slightly more often than naively expected because many .d.ts authors (mistakenly) create generic types which don't actually consume their type parameters. Perhaps this warning would effectively discourage them from doing so?