ahstro ahstro - 1 month ago 6
Javascript Question

How can I annotate I want any type as input but something of the same type as output with Flow?

Say I have a very simple function that simply takes an argument of any type and wraps it in an array.

function wrap (anything) {
return [anything]
}


That would be very easily described in (what I understand to be) Hindley-Milner annotation, like this:

// wrap :: a -> [a]


How would I go about using Flow's type annotation to show this same thing, i.e., that I want any type as input, and an array of that same type as output?

The following does not work:

function wrap (anything: a): Array<a> {
return [anything]
}


It throws this error:

ERROR in src/wrap.js:1
1: function wrap(x: a): Array<a> {
^ identifier `a`. Could not resolve name

Answer

This is the syntax for polymorphic functions:

function wrap<a>(anything: a): Array<a> {
  return [anything]
}