You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classAnimal{name: string;}classDogextendsAnimal{bark(){};}classCatextendsAnimal{meow(){};}classBox<V>{item: V;}functionf<TextendsBox<Animal>>(box: T){box.item=newCat();// <-- This is perfectly valid and allowed by the constraintreturnbox;// <-- The returned type is T}letresult=f(newBox<Dog>());// Type of 'result' is inferred as Box<Dog>result.item.bark();// <-- No compilation error. Run-time error..
Expected behavior:
Type of result should be inferred as Box<Animal>. result.item.bark(); should give a compilation error.
Actual behavior:
Type of result is inferred as Box<Dog>. result.item.bark(); does not error at compile-time but does error at run-time.
Comments:
Type of box should be widened from T to Box<Animal> within the body of the function, as there is no (current) way to ensure the members of box are not reassigned with types incompatible to the ones specified in T. The return type should therefore be Box<Animal> and not T.
[Edits: rewritten main example, heavily shortened and removed unneeded sections]