-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Check keys in code flow analysis #10515
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
Looks like a duplicate of the recently-filed #10515. |
@DanielRosenwasser #10515 is this issue. |
There are a few things here. First, playground is 1.8.0 at the moment, therefore does not have any code flow analysis, nor will 1.8.0 ever. Second, checking the keys is not a sufficient guard usually: const foo = { baz: undefined };
if ('baz' in foo) {
foo.baz.length; // Ooops!
} Second, when narrowing types, there are limits to the abilities for TypeScript to figure things out. Given you have two types, you should use a custom type guard to narrow it, versus relying upon other aspects. That way your type guard is attesting to the shape, instead of TypeScript having to try to track all the potential differences that would make it work: interface Foo {
bar: string;
}
interface CoolFoo extends Foo {
type: 'cool';
baz: string;
}
interface OtherFoo extends Foo {
type: 'other';
zip: string;
}
type SomeFoo = CoolFoo | OtherFoo;
function isCoolFoo(value: any): value is CoolFoo {
return value && value.type === 'cool';
}
function run(foo: SomeFoo): number {
if (isCoolFoo(foo)) {
return foo.baz.length;
} else {
return foo.zip.length;
}
} |
Uh oh!
There was an error while loading. Please reload this page.
TypeScript Version: playground / 2.1.0-dev
Code
Expected behavior:
Checking keys should be sufficient to check if
foo
is eitherCoolFoo
orOtherFoo
.In contrast checking by value works (at least in 2.1.0-dev, not playground):
But even with 2.1.0-dev I cannot check for existence by value. This does not work:
Not even that:
Actual behavior:
Checking keys is not enough to check if
foo
is eitherCoolFoo
orOtherFoo
. It doesn't compile, because TypeScripts treatsfoo
asCoolFoo | OtherFoo
even after checking keys.The text was updated successfully, but these errors were encountered: