Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flow generic type for function expression (arrow functions)

I usually try to keep flow function types separate from their implementation. It's a slightly more readable when I write:

type Fn = string => string;
const aFn: Fn = name => `hello, ${ name }`;

rather than:

const aFn = (name: string): string => `hello, ${ name }`;

When using generic types we can write:

const j= <T>(i: T): T => i;

const jString: string = j('apple'); // √
const jNumber: number = j(7);       // √

But how can I separate this type from a function expression?

type H<T> = (input: T) => T;
const h:H<*> = i => i;              // --> WHAT SHOULD GO FOR '*'?

const hString: string = h('apple'); // X error
const hNumber: number = h(7);       // X error

What should be used for *? any would work but that's not what I want.

In haskell this is a non-issue:

identity :: a -> a
identity a = a

identity "a-string" // √
identity 666        // √

See flow.org/try

like image 207
Sam R. Avatar asked Oct 05 '17 23:10

Sam R.


People also ask

How to add generic type in arrow function?

You can use a generic in an arrow function by setting it right before the function's parameters: const identity = <T>(value: T): T => value; The generic can then be passed when the function is invoked: 💡 The generics are specified right before the function's parameters using arrow brackets.

What is a 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.

How to create a generic function in JavaScript?

var add = function(a, b) { return a + b; } var addTo = add. magic(2); var say = function(something) { return something; } var welcome = say. magic('Hi, how are you? '); addTo(5) == 7; welcome() == 'Hi, how are you?


Video Answer


2 Answers

So I have noticed that if I use bounded generics, it'll work:

type H<T> = <T: *>(input: T) => T;
const h:H<*> = i => i;

const a: string = h('apple');      // √
const b: number = h(7);            // √
const c: {} = h({ nane: 'jon' });  // √

Don't ask me WHY.

like image 111
Sam R. Avatar answered Nov 03 '22 18:11

Sam R.


 type H<T> = (input: T) => T;
    const h2:H<*> = i => i;   
    const h3:H<*> = i => i;   
    const hString: string = h3('apple');
    const hNumber: number = h2(7);
like image 36
hosein khan beigi Avatar answered Nov 03 '22 16:11

hosein khan beigi