How to get Flow to understand the dynamic code that lodash uses for type checking at runtime?

An example of a dynamic thread code shows that a thread can compute type checking at runtime:

function foo(x) {
  if (typeof x === 'string') {
    return x.length; // flow is smart enough to see this is safe
  } else {
    return x;
  }
}

var res = foo('Hello') + foo(42);

But in real life, typeofnot good enough. I usually use verification functions like lodash ( _.isFunction, _.isStringetc.), _.isStringhandle a lot of extreme cases.

The problem is that if we change the example to use lodash for type checking at runtime, Flow no longer understands this:

function foo(x) {
  if (_.isString(x)) {
    return x.length; // warning: 'length' property not found in Number
  } else {
    return x;
  }
}

var res = foo('Hello') + foo(42);

I tried to use iflow-lodash, but it seems nothing has changed here .

, Flow , lodash ? Flow, .

+4
2

lodash libdefs.

Flow. , - .

function isString(x): boolean %checks { // << declare that the method is a refinement
  return typeof x === 'string';
}

function method(x: string | number): number {
  if (isString(x)) { // << valid refinement
    return x.charCodeAt(0); // << no errors
  } else {
    return x;
  }
}

[ ]

. , . Flow changelog .

, , .

function method(x: string | number): number {
  if (typeof x === "string") { // << Inline the check
    return x.charCodeAt(0);
  } else {
    return x;
  }
}
+13

:

if (_.isString(x) && typeof x === 'string') {

, , :

if (_.isString(x)) {
  // @ManuallyTyped
  var xStr: string = x;
  return xStr.length;
} else { ... }

// @ManuallyTyped suppress_comment , . , . .

, , Flow, , xStr string, .

0

Source: https://habr.com/ru/post/1654371/


All Articles