Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Assignability issue with function types and and subclass argument #5673

Closed
olivr70 opened this issue Nov 15, 2015 · 2 comments
Closed

Assignability issue with function types and and subclass argument #5673

olivr70 opened this issue Nov 15, 2015 · 2 comments
Labels
By Design Deprecated - use "Working as Intended" or "Design Limitation" instead

Comments

@olivr70
Copy link

olivr70 commented Nov 15, 2015

Hi
I stumbled on a strange behaviour which in my understanding is a bug (in Node with Typescript 1.6 and reproduced in the online Playground)

B is a subclass of A
It is possible to assign a variable F of type "function with A argument" with a value "function with a B argument".
This means that when calling F with a value of type A, the concrete function called will use some specific properties of B which are missing, leading to a runtime error

Olivier

class Mammal {
}
class Whale extends Mammal { 
    swim(duration:number) { /* some code */ } 
}

function swim10(w:Whale) { w.swim(10); }

type mammalFunc = (m:Mammal) => void;
function each(m:Mammal[], f:(Mammal) => void) { m.forEach(f); }

var f1:mammalFunc = swim10;
    // Problem : this should not be possible
var m1 = new Mammal();

f1(m1);
    // this compiles, but will fail at runtime because m1 has no swim() method
each([m1], swim10);
    // this compiles, but will also fail at runtime
@ahejlsberg
Copy link
Member

This is by design. See #222 and the explanation here. It is certainly possible to design rules that would disallow the example above (e.g. we could have strict contra-variance for parameters), but it would have far ranging undesired effects. For example, with strict parameter contra-variance, arrays would become invariant and a Whale[] wouldn't be assignable to a Mammal[]. That runs counter to everyone's expectations. So, in short, by fixing this we'd just trade one problem for another.

@ahejlsberg ahejlsberg added the By Design Deprecated - use "Working as Intended" or "Design Limitation" instead label Nov 15, 2015
@olivr70
Copy link
Author

olivr70 commented Nov 17, 2015

Thanks for the explanation. I missed it in the doc.

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
By Design Deprecated - use "Working as Intended" or "Design Limitation" instead
Projects
None yet
Development

No branches or pull requests

2 participants