[FIXED] How to make Ramda.is() function return another type

Issue

I am using Ramda.is to check types. But by default when i use it with array (Ramda.is(Array)) it returns val is unknown[] type. If there are any options to make it return val is any[] using generics for examle. Or the only option is to do something like that (val: any): val is any[] => R.is(Array)(val).

The problem is here

Solution

The signature of R.is is:

is(ctor: any, val: any): boolean;
is(ctor: any): (val: any) => boolean;

So the return value is always a Boolean.

However, in your case you don’t care about the result of R.is, you want to set the type of the value passed to val to be any[] if R.is returns true.

To do that, you can use a type predicate that will "mark" the passed value:

const isArrayWithType = (val: any): val is any[] => is(Array, val);

And if we use it as a guard, TS will now know that whatever we passed as val is of type any[]:

const arr: unknown = [1, 2, 3];

if (isArrayWithType(arr)) {
  arr.push(4); // arr type is any[]
} else {
  arr.push(5); // arr type is unknown
}

See working example

Answered By – Ori Drori

Answer Checked By – Senaida (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published