-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Typecast to any
in one array element affects other elements
#26184
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
Comments
The algorithm for checking the program works like this:
The net result is "wrong" but every individual step in that logic is right and can't really be changed without breaking something else (including being a breaking change in existing code). You can cast to |
@RyanCavanaugh Typechecking array literals as tuples (which we had mentioned elsewhere for other things) would actually solve this. |
@weswigham in addition to being a breaking change, it still leaves problems like var x = ["", 1 as any]; // presumably still widened to any[]?
var y: number[] = x; |
Would it be possible to treat literals differently if their target type is known in advance? Here are a few examples: // Assignment to variable of known type
const foo: SomeType = [...];
// Function argument of known type
function foo(arg: SomeType);
foo([...]);
// Property of known type
const foo: { bar: number[] } = { bar: [...] }; I know that there are other languages that do this. But I have no idea whether that's feasible for TypeScript. |
We tried doing this - see #19541 - and ran into some architectural problems. We should try again, though |
@RyanCavanaugh Did you mean to close this issue, while marking the other (#32165) as a duplicate? |
I agree we should leave this one open, i closed mine. |
TypeScript Version: 3.1.0-dev.20180803
Search Terms:
any
,object
,array
, "is not assignable to type"Code
Expected behavior:
I expect two build errors: One for the assignment of
x
, one fory
.This is because both
x
andy
are assigned values of the wrong type. In both cases, not all array elements contain a propertyfoo
of typenumber
.Actual behavior:
There is no build error for the assignment of
x
, only for the assignment ofy
. This is the build output:In the assignment of
x
, thefoo
property of the second array element is converted toany
. Rather than converting only this one value toany
, TypeScript seems to convert thefoo
properties of all array elements toany
.Playground Link: Playground demo
Related Issues: none
The text was updated successfully, but these errors were encountered: