Skip to content

type checking after instainceOf condition is working incorrectly #5522

Closed

Description

this example works great

function test(value: string[]| string){
    var result: string;
    if (value instanceof Array){
        result = value.join('');
    }
}

but this

interface IFoo {
    value: string[] | string;
}

function bar(options: IFoo) {
    var result: string;
    if (options.value instanceof Array) {
        result = options.value.join('')
    }
}

property join does not exists on type string[] | string

i think i'ts compiler mistake

Activity

  1. kitsonk commented on Nov 4, 2015

    @kitsonk
    Contributor

    I maybe wrong, but I don't think the type narrowing will work on complex types like that, I would suspect because it would over complicate what the compiler would have to keep track of, duplicating the complex type and then narrowing the one element of the type... In order to get it to work, you should try something like:

    interface Foo {
      value: string[] | string;
    }
    
    function bar(options: Foo) {
      let result: string;
      const value = options.value;
      if (value instanceof Array) {
        result = options.value.join('');
      }
    }
  2. stepancar commented on Nov 4, 2015

    @stepancar
    Author

    Kitson Kelly (@kitsonk) , thank you for your answer!
    I agree that, this checking is more harder, but i think it's more usefull for developers.
    In your solution you added const value only for force compiler to check. I think it's not good idea

  3. mhegazy commented on Nov 4, 2015

    @mhegazy
    Contributor

    looks like a duplicate of #4297

  4. added
    Duplicate
    on Nov 4, 2015
  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

    Duplicate

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions