Regression in 1.0RC: Constraint of a type parameter cannot reference any type parameter from the same type parameter list

Topics: Language Specification
Mar 9, 2014 at 5:28 PM
After upgrading from Typescript 0.9.5 to 1.0RC, I see new compilation errors in code like this:
interface Dispatch {
    load<A extends Action<T>, T>(action: A, onSuccess: (t: T) => any): void;
or like this:
class TableSection<R extends TableRow<C>, C extends TableCell> {
The compilation error is: Constraint of a type parameter cannot reference any type parameter from the same type parameter list.

Such constructs work in Java and C#, and used to work in Typescript 0.9.5. Why were they prohibited in 1.0RC and is there a chance to get them back? The above examples demonstrate that it's a useful language feature.
Mar 10, 2014 at 4:45 PM
Edited Mar 10, 2014 at 6:24 PM
The primary reason we now disallow this is that recursive constraints (i.e. constrains that reference their own type parameter) introduce significant complexities in the type checker. However, in your examples above the constraints aren't actually recursive, but rather some of the type parameters look to just be shorthand for types constructed from other type parameters. That's usually not a good idea as it limits what kind of type inferences can be made. In general you'll do better by always reducing the number of type parameters to the smallest possible set of truly independent types. For example, a better way to write the first declaration is:
interface Dispatch {
    load<T>(action: Action<T>, onSuccess: (t: T) => any): void;
This more accurately reflects that there is only one type, T, that varies and allows inferences made from an argument for 'action' to flow into the callback:
var a: Action<string>;
var d: Dispatch;
d.load(a, t => /* Type of t is inferred to be string */ ...);
The same is true for your second example. It is probably better to write:
class TableSection<C extends TableCell> {
    // Substitute TableRow<C> for usages of R everywhere
Mar 10, 2014 at 8:30 PM
Thanks, I was able to redesign my code according to your suggestions.

P.S.: Anders, thank you for TypeScript, it's a wonderful language for making complex web applications, it's superior to other technologies, and it's a pleasure to write in it.