-
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
Add a pedantic array variance option #40939
Comments
From a UX perspective, limiting this to arrays sounds like a reasonable idea, as they’re used everywhere and frequently mutated. From a type system perspective, there’s nothing special about arrays, and strict variance for them would arise naturally if we turned off bivariance for methods and/or calculated read-write properties and index signatures as invariant. This isn‘t to say that a special case couldn’t be carved out for arrays, but it would raise some weird design questions about types that are structurally array-like but not an instance of the global |
I believe arrays are a special case, in checker.ts |
They are a special case for performance reasons—because we control the shape of the Array interface, we can know in advance how the variance would compute structurally, so we skip it. If we were to change that special case, it would essentially mean that our shortcut returned the wrong result, which would have the weird effects I mentioned. |
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Search Terms
variance array
Suggestion
Currently, TypeScript allows assignment from
D[]
toB[]
whenD
is a subtype ofB
.Providing a configurable option to control if arrays are covariant (current behavior) vs invariant per project would allow for the user to take advantage of a more sound type system. Additionally, the assignment of a
D[]
to areadonly B[]
is sound and should also be permitted when "pedantic array variance" is specified.Use Cases
Having the type-checker treat arrays as invariant will allow the compiler to catch a class of issues that are currently not caught. Allowing covariant arrays can be a source of subtle bugs that are hard to track, and many projects do not benefit from having covariant arrays.
By allowing this to be configurable and having the default behavior assume covariant arrays, backwards compatibility is maintained but the user may also opt in to a more sound type system.
Examples
With pedantic array variance, assignment of
arr
toref
would produce a diagnostic.Checklist
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered: