Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flow type an array of values with generics

The following code

type Value<T> = {|
  name: string,
  value: T,
|}

const myNumber: Value<number> = { name: 'number', value: 1 };
const myString: Value<string> = { name: 'string', value: 'foo' };

const arr: Array<Value> = [myNumber, myString];

I want to loop through an array of Value objects and get the name value of all my objects, but I'm getting this error:

9: const arr: Array<Value> = [myNumber, myString];
                    ^ Cannot use `Value` [1] without 1 type argument.
References:
1: type Value<T> = {|
             ^ [1]

Any ideas how to fix this without using Value<any>? I'm using flow strict

Flow Playground link

like image 467
Yangshun Tay Avatar asked Dec 05 '25 22:12

Yangshun Tay


1 Answers

Update In latest version (tested with 0.98.0) flow is able to infer the types properly, so explicit annotation is no longer required. Just go with:

const arr = [myNumber, myString];

Older versions:

In flow you could use Existential Type (*)

An existential type is used as a placeholder to tell Flow to infer the type

const arr: Array<*> = [myNumber, myString];

Playground

like image 119
Aleksey L. Avatar answered Dec 08 '25 11:12

Aleksey L.