Skip to content

Type guard functions seem to only set the type when used directly #10172

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

Closed
jvanoostveen opened this issue Aug 5, 2016 · 3 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@jvanoostveen
Copy link

TypeScript Version: typescript@beta (2.0)

Code

// Setup
interface A {
  value: string;
}
interface B {
  property: string;
}
type AorB = A | B;

let isB = (obj: any): obj is B => {
  return obj.hasOwnProperty('property');
};
// Setup end


let output = (obj: AorB) => {
  if (isB(obj)) {
    console.log(obj.property); // <-- works

    let values = (new Array(100)).map(a => obj.property); // <-- Property 'property' does not exist on type 'A | B'
    console.log(values);
  }
};


let someObj: B = { property: 'value' };
output(someObj);

Expected behavior:
obj.property within the map should still know its type. This works fine in pre-2.0.

Actual behavior:
The compiler does not recognise property as part of obj within the map.

@jvanoostveen
Copy link
Author

In some of our existing code I get the following error on similar structures:
Error TS2339: Property 'value' does not exist on type 'never'.

@kitsonk
Copy link
Contributor

kitsonk commented Aug 5, 2016

This is a dupe of #7719 and so many others. Specifically the comment is here as to why it is the way it is. The team is considering allowing parameters to be declared as const to indicate they will not be changed within a function.

@jvanoostveen
Copy link
Author

Looks like I searched for the wrong terms :). Continue on the referenced issue then.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Aug 5, 2016
@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
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants