Reputation: 6531
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
Upvotes: 3
Views: 1570
Reputation: 1352
It is able since v0.72. CHANGELOG. Example
// @flow
declare function makeFoo<T>(): T;
const t = makeFoo<number>();
(t: number);
// $ExpectError
(t: string);
Upvotes: 2
Reputation: 494
Generics can be used for specifying a relation between arguments or arguments and a result. You can`t use it at "call time", only on declaration.
It makes you write more unmistakable code - it`s better to have 2 functions than one universal (from point of understanding and typing):
function eatNumbers(v: number): string {return "" + v;}
function eatSomething<T>(v: T): T {return v;}
Upvotes: 1