-
Notifications
You must be signed in to change notification settings - Fork 12.7k
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
Define assignability relation for primitive-constrained type parameters #2694
Comments
If primitive types aren't allowed to be extended, then how is writing Someone could always write the above function this way, which I think makes more sense:
Or maybe I'm missing something? |
See the examples |
Ok, that makes sense. Btw, it might be beneficial to add the ability to constrain by |
It's not only primitive types where the lack of assignability of a type parameter to its constraint hurts; I've also run into this with unions. Here's a real example of that:
It gets even worse with class hierarchies:
I don't understand why subtyping/assignability of type parameters needs to have a separate rule for every kind of constraint (object, primitive, union, another type parameter, ...) - seems that just one general rule should suffice: "S is a type parameter, and S's constraint is (a subtype of|assignable to) T." |
Approved |
@jeffreymorlan the unions issue is fixed by #2778. But as you mention, it does seem silly that every kind of constraint has to be accounted for. Probably the more correct thing to do is to recursively check if the base constraint of S is assignable to T |
I stumbled across this ancient issue and if I'm understanding it correctly I think it can be closed. These days code like this legal: function f<T extends number>(x: T) {
const y: number = x // no error
} |
The spec does not define any case in Assignment Compatibility where
S
is a type parameter constrained to a primitive type andT
is that same primitive type.This leads to some weird errors, e.g.
T
is not assignable tonumber
even thoughT extends number
:See also http://stackoverflow.com/questions/29545216/inconsistent-behavior-of-enum-as-constrained-parameter-in-generic
The text was updated successfully, but these errors were encountered: