Generic type references must include all type arguments

Topics: General
Jun 19, 2013 at 2:23 PM
I remember when generics was being defined for TypeScript, that it would implicitly use "any" if no type was defined. Now I'm seeing that it is always required.

I probably missed the discussion somewhere, but why was this changed?
Jun 20, 2013 at 3:28 AM
The way type inference and type parameter inference works has changed a bit over time as we try to strike the right balance of correctness and usability with various other features. Currently the type parameter is explicitly required for generics used in a type position, it shouldn't be required in expressions (except perhaps in some cases where an explicit type parameter is necessary to disambiguate a function call for example). Some of the reasoning for this is that it's a fairly easy mistake to make (omitting a type parameter) which combined with the assignment compatibility rules for 'any' and type inference leads to some unfortunate circumstances. Consider:
class C<T> { foo(x: T) { } }

var x: C = new C<number>();
x = new C<string>();
If this definition of x were allowed then it becomes unfortunately easy to make a mistake like above or otherwise have 'any' start leaking into later calls due to type inference. Since this doesn't impact existing JavaScript code and you have explicitly opted in to using generics in your Typescript we felt that requiring the type parameters in these type positions was better for preventing common errors without being onerous syntactically. Note that type inference still works in such a way that you will not be required to write type annotations in many cases. For example:
class C<T> { foo(x: T) { } }
class D<T> {
    constructor(x: T) { }
    foo(x: T) { }

var x = new C(); // C<any> is inferred
var x2 = new D('hi'); // D<string> is inferred
x2 = new D(123); // error, D<number> is not compatible with D<string>
Does that match your expectations?
Jun 20, 2013 at 9:43 AM
Hi Dan,

This makes perfect sense, thank you for this explanation!