0

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).

1 Answer 1

1
+50

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.