Skip to content

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

Description

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.

Activity

  1. kitsonk commented on Jul 2, 2016

    @kitsonk
    Contributor

    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?) Mohamed Hegazy (@mhegazy) Anders Hejlsberg (@ahejlsberg) Ryan Cavanaugh (@RyanCavanaugh)

  2. ahejlsberg commented on Jul 3, 2016

    @ahejlsberg
    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.

  3. ulrikstrid commented on Jul 3, 2016

    @ulrikstrid
    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.

  4. mquandalle commented on Jul 19, 2016

    @mquandalle

    Anders Hejlsberg (@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?

  5. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions