Skip to content
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

Type guards don't work for interfaces with only optional properties #5842

Closed
domoritz opened this issue Nov 30, 2015 · 1 comment
Closed
Labels
By Design Deprecated - use "Working as Intended" or "Design Limitation" instead

Comments

@domoritz
Copy link

For some reason type guards to not work if an interface has only optional properties.

interface A {
  foo : number;
}

function isA(object: any): object is A {
  return true;
}

let a: A | boolean;

if (isA(a)) {
  a.foo;   // compiles
}



interface B {
  foo? : number;
}

function isB(object: any): object is B {
  return true;
}

let b: B | boolean;

if (isB(b)) {
  b.foo;  // does not compile because type inference says its `B | boolean`
}
@mhegazy
Copy link
Contributor

mhegazy commented Dec 1, 2015

For a type guard, it will look through all the union type constituents (B and boolean in the example), and will filter out types that are not assignable to the target type. since B has only optional properties, booelan is assignable to, and it is not filtered out from the union. looks like a good candidate for #3842.

a work around is to tag type B, see #4895

@mhegazy mhegazy closed this as completed Dec 1, 2015
@mhegazy mhegazy added the By Design Deprecated - use "Working as Intended" or "Design Limitation" instead label Dec 1, 2015
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
By Design Deprecated - use "Working as Intended" or "Design Limitation" instead
Projects
None yet
Development

No branches or pull requests

2 participants