I am trying to use an existential type in a case where I have to pass a function that returns a React component to an external TS library – in this case, I don’t care what the react component is, just that it is component like. At first, I did this by just unsafely casting components to an abstract type.
// This function is passed to the TS library
switch prop {
| #person => PersonNode.make->castToAny
| #org => OrgNode.make->castToAny
| #userCreated => UserCreatedNode.make->castToAny
| #default => UserCreatedNode.make->castToAny
}
I learned about existential types recently and tried the below and was met by the following error
type rec anyComponent = AnyComponent: React.componentLike<'a, 'b> => anyComponent
Constraints are not satisfied in this type.
Type
React.componentLike<'a, 'b> => anyComponent
should be an instance of
anyComponent
I tried to simplify this to the simplest OCaml example that would compile:
type any = Any : 'a -> any
let _ = Any "Hello World"
let _ = Any 1
The equivalent Rescript of this simplified example doesn’t work with the same error:
type rec any = Any: 'a => any
Everything works of course if I pass along the type parameter to the return type of the constructor signature, but that defeats the purpose of an existential in this case: hiding the type information that I don’t care about.
Does Rescript not support this kind of type or am I not notating it correctly? Casting to an abstract type somewhat works but feels inelegant.