-
Notifications
You must be signed in to change notification settings - Fork 12.5k
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
Support type guards on property access expression #3812
Comments
I believe I ran into similar cases when first playing with #1260. This is by design (4.20): |
is not this a duplicate of #1260? |
Upon reflection probably yes unless there's something unique about the more recent changes to type guards supporting basic property access but not instanceof/user defined type guards |
instance of and use type guards are just two checks, if we allow narrowing by property access, we will need to add it every where, typeof, instanceof, type guards ..etc.. |
Yeah, that's what I figured, will just close this then. |
I don't think #1260 and this are really the same thing |
The following example demonstrates the problem, which still exists in interface Foo {
myProperty: (boolean | string)
}
var foo: Foo = {
myProperty: "Hello World"
};
var p = foo.myProperty;
if (typeof p === "string") {
// This works fine!
console.log(p.length); // Prints `11`
}
if (typeof foo.myProperty === "string") {
// This line produces the following compilation error:
// "Property 'length' does not exist on type 'boolean | string'."
console.log(foo.myProperty.length);
} |
This will be going in as part of the non-nullable type work |
Closed in #7140. |
I just found out that property access expressions doesn't work on type predicate functions and
instanceof
type guards.I'm not sure if there is an easy fix on this problem. We are provided just a symbol when narrowing. That symbol represent the left most expression and then we walk up the if statement. There is no easy way of controlling symbol by symbol on each namespace in a property access expression in the if-statement-body. Because there is no info about the property access expression provided in
getTypeOfSymbolAtLocation(symbol: Symbol, node: Node)
.I also found that type assertion expressions are also not working in type predicate functions. But I will land a fix on that.
The text was updated successfully, but these errors were encountered: