XeniaSis
XeniaSis

Reputation: 2354

typescript: instanceof not working with immutable.js types

We are trying to update our project from typescript2.4 to typescript3.2. We stumbled upon the following problem with immutable.js.

Previously just using if(x instanceof Immutable.Iterable) meant that in the if block the type of x was Immutable.Iterable<any, any>. However, after updating typescript, the inferred type of x is {}.

Code snippet

enter image description here

Wrong type inferrence

enter image description here

It would be really nasty to fix all the errors by using x as Immutable.Iterable<any, any>.

I guess the problem lies with immutable.js because any other types are inferred correctly in the if block.

P.S. I know about the fact that instanceof is not always trustworthy (https://github.com/facebook/immutable-js/issues/450#issuecomment-107238770) but using Immutable.Iterable.isIterable() doesn't provide the type support that we need (since the variable is still of type any).

Upvotes: 0

Views: 458

Answers (1)

Karol Majewski
Karol Majewski

Reputation: 25790

Create a type guard:

const isIterable = (argument: any): argument is Iterable<any> =>
  Symbol.iterator in argument

Usage:

declare const foo: number | Iterable<number>;

if (isIterable(foo)) {
  console.log(...foo);
}

The version of immutable I have installed is 4.0.0-rc.12. It doesn't expose a class called Iterable. Instead, it relies on the Iterable interface built-in the standard JavaScript library.

Upvotes: 1

Related Questions