You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Incorrect type inference when using object index #17011
Expected behavior:
Typescript should be able to infer that paramsObject[key] is still a string or string array after Array.isArray has been called. It can't change.
It works correct if I assign paramsObject[key] to a variable beforehand, and then use that variable in both the check and the doArray and doString.
Actual behavior: Argument of type 'string | string[]' is not assignable to parameter of type 'string[]' for doArray
and Argument of type 'string | string[]' is not assignable to parameter of type 'string'. for doString
I made the example in the OP in the playground, so i'm pretty sure typescript complains, and I have seen it in my local code, that's why i noticed in the first place.
Rasmus Hansen (@zlepper) Andy reduced your example to a more minimum reproducible which exhibits the behaviour. In other words, he is suspecting it is an issue.
The OP example is working as intended. In the example the index expresssion is a variable and not a string literal. I don't think it is likely we'll ever do control flow based narrowing of obj[x] expressions where x is a variable since we'd also have to track that there are no intervening assignments to x. I suggest changing the code to:
Activity
zlepper commentedon Jul 7, 2017
I made the example in the OP in the playground, so i'm pretty sure typescript complains, and I have seen it in my local code, that's why i noticed in the first place.
kitsonk commentedon Jul 7, 2017
Rasmus Hansen (@zlepper) Andy reduced your example to a more minimum reproducible which exhibits the behaviour. In other words, he is suspecting it is an issue.
ahejlsberg commentedon Jul 7, 2017
Andy (Andrewkraft) (@Andy-MS) Your example is a duplicate of #10530, but isn't the same as the OP.
The OP example is working as intended. In the example the index expresssion is a variable and not a string literal. I don't think it is likely we'll ever do control flow based narrowing of
obj[x]expressions wherexis a variable since we'd also have to track that there are no intervening assignments tox. I suggest changing the code to:This behaves as expected and is also more efficient.
zlepper commentedon Jul 7, 2017
That is also what i wrote in the OP
I just wanted to make sure it was intended. Thank you!
And thanks for the Great language :)
ahejlsberg commentedon Jul 7, 2017
Rasmus Hansen (@zlepper) Right, I missed that. And you're welcome!