-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
Array.isArray guard drops the type of the #56842
Comments
Also: Issue title drops the object of the |
@jcalz #33700 is definitely related, but see below. You only lose the array type here because the value is narrowed to declare const myConst: MyInterface | Array<MyInterface>;
if (Array.isArray(myConst)) {
// const myConst: MyInterface[]
myConst[0].thisPropertyDoesNotExist = "world"; // error
myConst.someProperty = "world"; // also error
}
|
This is correct behavior. On this line you said const myConst: MyInterface | Array<MyInterface> = { someProperty: "hello" }; TypeScript can see this line of code, and can see that So then when you write if (Array.isArray(myConst)) { The only situation where this is If the initializer of |
@RyanCavanaugh Is it a bug that |
But we do know. The array is typed before the if, and elements should have the same type inside the if. |
No, |
The declared type, yes, but the value is narrowed on assignment (TS knows that you didn't assign an array so removes that possibility from the union) so the type system has essentially "forgotten" about the array type by the time you do the |
This issue has been marked as "Working as Intended" and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
π Search Terms
isArray
π Version & Regression Information
Bug occurs in 5.3.3
β― Playground Link
https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgLIE8CS5rycgbwChlkBnAewFsIAFKCgB2jHQC5ywpQBzAbiIBfIkQQUQZMMiroAwuMkcM2SLEQoAPsgCCUKHHQAeZTjVIAfMgC8hctToNmUVhwBEACwgAbLxVfJBASJgGGQACl19dAA6YDJIgzCZeQkwAEo0whJkAHoc5DFU6TkFMCUsUzwUADJkOBB0AG0AXWzk0saABmbosHc4+iYWdAARCggyADkKMABRAA84qRtXAHcKKC8AE1c+XPzZ1ei2ktToyhpBp1ZrZDWN7d395EPj4SIYAFcQBDBgcWQACMIGBVJh4noDIYACrmMIwCgUDjQ5BaBJGWFpDgIijIOI6SEYyzEUhQEGfKAgAlRWIQqLwxFpATvELhYGg6Dg9FJU6SDJZUh5ZBXYbIADkfQGjmGYwm0zmi0kYuQW3GZGQIBmyAgiqkANYzHFJlUVTFvTIYQATABma0ATjSJxSki6PUlZBFzlGavlCyWt3umx2QUF+QAyn8fECGABrCAgY6kdpnC4OIZegPrIO7IREIA
π» Code
π Actual behavior
It compiles.
π Expected behavior
Accessing thisPropertyDoesNotExist should be an error.
Accessing someProperty when isArray says it's an array should be an error.
Additional information about the issue
No response
The text was updated successfully, but these errors were encountered: