When checking if two class types are assignable, don't check the assignability of their private member variables #49144
Labels
Working as Intended
The behavior described is the intended behavior; this is not a bug
Suggestion
🔍 Search Terms
private member variables
assignability
contravariant
✅ Viability Checklist
My suggestion meets these guidelines:
⭐ Suggestion
When checking if two class types are assignable, don't check the assignability of their private member variables.
📃 Motivating Example
playground link
I would expect the assignment above to be safe, even though Function types are contravariant in their arguments, because the
fn
member variable is private, and the innerBag
code only has access to an arbitraryT
.💻 Use Cases
The most common use-case I've run into is wanting to have a function in the client code that takes
Bag<unknown>
as a parameter:My intent here is for the
clientFn
to explicitly not care about the innerT
. Note that this could be fixed by usingany
, and while I don't likeany
in general, maybe this could be a good time for it?Another use-case might be where client code wanted to create a list of Bags, where the
T
s are constrained to an allowable set:Note, this can be fixed by changing the
AllowedBagTypes
type toBag<number> | Bag<string>
.One final thing to note is that this
Bag
class breaks the client code only because of the privatefn
member variable. That means that adding such a variable to an otherwise working existing class could unexpectedly break client code.I'm not 100% sure this is actually a safe suggestion, and I'd be very happy to be corrected if I'm wrong! I think most of the use-cases can be fixed by using
any
or by changing the types in the client code around, so this may not be a super valuable suggestion for the effort. But just figured I'd put it out there!The text was updated successfully, but these errors were encountered: