Confused About Bounded Polymorphism Syntax
While reading about Bounded Polymorphism and Generics, I've been trying to apply the concepts to my function types. In the generic type docs, it indicates that Bounded Generics can be used with arrow function declarations.
You can use generics in the same places you’d add any other type in a function type (parameter or return types).
<T>(param: T) => T
However, while testing this example in Try Flow, I'm getting errors about incompatible initiation of T. Here's the code I'm testing.
// Type
type Example = {
identity: <T>(param: T) => T,
};
// Implementation
function example(): Example {
return {
identity: (param) => param,
}
}
In type Example, <T> is declared directly before the arrow function type, but that's what produces the error. Alternatively, it could be declared directly after type Example to resolve the error.
type Example<T> = {
identity: (param: T) => T
};
However, the <T> generic is no longer using Bounded Polymorphism on the identity function, and it must be given a value whenever Example<string> is used. This defeats the purpose of the generic for my use cases. I'm trying to preserve the <T>(param: T) => T functionality in my original example and the docs.
What am I missing? Thanks!
Flow can't infer polymorphic functions, so you have to annotate them explicitly:
type Test = {
identity: <T>(param: T) => T,
};
function tester(): Test {
return {
identity: <T>(param:T):T => param,
}
}
@vkurchatkin Oh, that makes sense, thank you. So is there any way to create a Type Alias for a polymorphic function? I'm trying to create a function type that I can import/export across files without redeclaring the type signature each time.
// file1.js
export type IdentityFn = <T>(x: T) => T;
const identity: IdentityFn = (fn) => (...args) => fn(...args);
// file2.js
import type { IdentityFn } from './file1.js';
const makeUtils = (identity: IdentityFn) => ({
identity: identity,
});
type IdentityFn = <T>(x: T) => T; is fine. The only thing to remember is that in order to assign a function to this type you have to make it polymorphic explicitly.