Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to explicitly pass type arguments to generic functions in flow?

I'm trying to explicitly specify the type when calling a generic function.

For example:

export function gen<T>(a: string): { eat: T => string } {
  return {
    eat: (v: T): string => a
  };
}

Of course, using C++-like syntax doesn't work, because flow extends Javascript syntax, and this is already a valid JS expression (a comparison):

const { eat } = gen<number>("str")

What is the correct syntax?

I want to pass a type explicitly, because otherwise this sort of code won't produce an error:

const { eat } = gen("str")
const a = eat(5)
// I want this to be an error, but it is not
const b = eat("foo")

I can of course annotate the assignment, causing the desired generic type to be inferred, but that can be cumbersome. Try it here

like image 268
aij Avatar asked Nov 24 '25 06:11

aij


1 Answers

It is able since v0.72. CHANGELOG. Example

// @flow

declare function makeFoo<T>(): T;

const t = makeFoo<number>();

(t: number);

// $ExpectError
(t: string);
like image 76
re-gor Avatar answered Nov 25 '25 20:11

re-gor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!