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

Doesn't remember the class inside a Array.map #9491

Closed
ulrikstrid opened this issue Jul 2, 2016 · 4 comments
Closed

Doesn't remember the class inside a Array.map #9491

ulrikstrid opened this issue Jul 2, 2016 · 4 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@ulrikstrid
Copy link

TypeScript Version: nightly (2.0.0-dev.201xxxxx)

Code

class SomeClass {
  constructor(public id: number){}
}

class SomeOtherClass {
  constructor(public name: string){}
}

type SomeUnionType = SomeClass | SomeOtherClass;

function buggyFunction(aArray: string[], bug: SomeUnionType): void {
  if (bug instanceof SomeClass) {
    console.log(bug.id);
    return;
  }

  if (bug instanceof SomeOtherClass) {
    aArray.map((a) => a = bug.name());
    return;
  }

  return;
}

Expected behavior:
Typescript should know that bug is of the type SomeOtherClass inside of the map function.

Actual behavior:
Property 'name' does not exist on type SomeClass | SomeOtherClass.

@kitsonk
Copy link
Contributor

kitsonk commented Jul 2, 2016

Duplicate of #9263 and #7662 and #9345 as narrowing is currently reset across function boundaries as explained in #7718 (comment).

Though this keeps coming up and it seems logical that anonymous functions, this could be potentially preserved? (or at least arrow functions used as callbacks?) @mhegazy @ahejlsberg @RyanCavanaugh

@ahejlsberg
Copy link
Member

The solution here is to guard on a const variable. Type guards are in effect across function expression and arrow function boundaries for const variables. We are considering allowing const as a parameter modifier so you don't have to copy parameters into const locals.

@ulrikstrid
Copy link
Author

Yeah, I solved my real issue by assigning the value to a const but it seems wrong to have to that. The behaviour is the same when using interfaces with a .kind property as guard.

@mhegazy mhegazy added the Question An issue which isn't directly actionable in code label Jul 4, 2016
@mhegazy mhegazy closed this as completed Jul 4, 2016
@mquandalle
Copy link

@ahejlsberg

We are considering allowing const as a parameter modifier so you don't have to copy parameters into const locals.

I’m interested in that, is there an issue to track this solution?

@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
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

5 participants