Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Flow generic functions syntax

I'm facing some syntax errors when trying to write generic map function.

function mymap<A, B>(fun: (_: A) => B, array: Array<A>): Array<B> {
    let result: Array<B> = [];
    for (let i of array)
        result.push(fun(i));
    return result;
}

let x = mymap<number, number>(x => x, [1, 2, 3]);
                            ^ Unexpected token    

Flow says: Unexpected token >. What am I doing wrong? Thank you for your help.

like image 646
zyks Avatar asked Apr 22 '17 15:04

zyks


People also ask

How do you write a generic function?

Functions can create generics by adding the type parameter list <T> before the function parameter list. You can use generics in the same places you'd add any other type in a function (parameter or return types). function method<T>(param: T): T { // ... } function<T>(param: T): T { // ... }

What is Flow function in JavaScript?

Flow is a static type checker that allows a developer to check for type errors while developing code. This means a developer receives faster feedback about the code, which they can use to improve its quality. Flow works by using annotations and type definitions for adding type checking support to your code.

What is generic flow?

Generic Flow Control is employed in the header of the ATM (Asynchronous Transfer Mode) cell at the UNI (User to Network Interface) interface. It is used to define a multiplicity of users at a common interface.

What is Flow function?

(definition) Definition: An assignment of flow values to the edges of a flow network that satisfies flow conservation, skew symmetry, and capacity constraints. Also known as network flow. See also saturated edge.


1 Answers

Flow is a type checker only. While it doesn't allow type overloading of generic implementation, you shouldn't specify types while you call a function. Flow will just try to check arguments for compatibility with the signature of the function and deduct the output type. So you just need to write

let x = mymap(x => x, [1, 2, 3]);

and Flow will deduct the output type of the expression and apply it to the x variable.

Or you can explicitly specify a type of x:

let x: Array<number> = mymap(x => x, [1, 2, 3]);

In this case Flow can compare a deducted type with the required type, and if you erroneously will use an incorrect mapping function like x => x.toString(), then Flow will warn you about that:

   let x: Array<number> = mymap(x => x.toString(), [1, 2, 3]);
//              ^ string             ^ This type is incompatible with number
like image 62
artptr Avatar answered Sep 28 '22 10:09

artptr