-
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
Errors issued for working code due to narrowing behaviour #7160
Comments
In branches 2 and 4, the compiler could safely infer that |
Technically, the value for |
Do you have a compelling use case? I don't see you actually modifying |
Hi @DanielRosenwasser, sorry I lost track of this for a while. Is this example any clearer? // Overlapping interfaces, neither is a 'subtype' of the other.
// These might be used for cross-cutting feature/capability detection.
interface AB {a;b;}
interface BC {b;c;}
function isAB(x: any): x is AB { return x && x.a && x.b; }
function isBC(x: any): x is BC { return x && x.b && x.c; }
interface Other {d?;e?;f?}
// A function that works with objects with varying capabilities...
function test(x: AB | BC | (AB & BC) | Other) {
if (isAB(x)) {
if (isBC(x)) {
// This is where AB and BC overlap, so we must have an AB&BC
// This works fine at runtime, but not at compile time.
console.log(x.a, x.b, x.c); // ERROR: Property 'c' does not exist on 'AB'
}
else {
console.log(x.a, x.b);
}
}
else {
console.log('other');
}
}
// Runtime results:
let a = 'A', b = 'B', c = 'C';
test({a}); // other
test({b}); // other
test({c}); // other
test({a,b}); // A B
test({a,c}); // other
test({b,c}); // other
test({a,b,c}); // A B C As for the original example, it was the result of me trying to work with the code in this comment, which was presented as the explanation for #7045, but looked out of step with runtime behaviour to me. |
I was hoping this way of using type guards might work now that #8010 has landed, but it still doesn't :( Is there any hope for this 'feature-detection' style of type guards to get better type checking? |
This should be working as intended in latest. |
Yes, the OP example now works, but the second example still doesn't compile (but is runtime-valid code). I take it this fix is due to @weswigham's work in #8993, which resolves the OP problem through primitive narrowing. The second example is really a different problem with no primitives involved. I'll re-post that as a separate issue. This is a really helpful improvement to type guards, thanks. |
The second example is now fixed via #9031. |
TypeScript Version:
nightly (1.9.0-dev.20160217)
Code
Expected behavior:
No compile-time or runtime errors, and outputs
"(1) string a (3) thing b (2) thing c"
Actual behavior:
No runtime errors, and outputs
"(1) string a (3) thing b (2) thing c"
as expected, but compiler issues two errors as shown in code comments.The text was updated successfully, but these errors were encountered: