Skip to content

type checking after instainceOf condition is working incorrectly #5522

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
stepancar opened this issue Nov 4, 2015 · 3 comments
Closed

type checking after instainceOf condition is working incorrectly #5522

stepancar opened this issue Nov 4, 2015 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@stepancar
Copy link

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

@kitsonk
Copy link
Contributor

kitsonk commented Nov 4, 2015

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('');
  }
}

@stepancar
Copy link
Author

@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

@mhegazy
Copy link
Contributor

mhegazy commented Nov 4, 2015

looks like a duplicate of #4297

@mhegazy mhegazy closed this as completed Nov 4, 2015
@mhegazy mhegazy added the Duplicate An existing issue was already created label Nov 4, 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
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants