[ This is not this ]
Take a look at this snippet of code:
interface Machine<OpaqueType> {
get(): OpaqueType,
update(t: OpaqueType);
}
const f = <U, V>(uMachine: Machine<U>, vMachine: Machine<V>) => {
const u = uMachine.get();
vMachine.update(u);
}
The error shown when trying to compile the last line reads as follows: “Argument of type 'U' is not assignable to parameter of type 'V'. 'V' could be instantiated with an arbitrary type which could be unrelated to 'U'.”
Indeed! I have two machines that can each handle their own parts independently but not together without explicit coordination.
However, the usage of <U, V>
seems unnecessary. The function doesn't really care about the specific types involved. It would be ideal to write it in a simpler way like this:
const f = (uMachine: Machine<unknown>, vMachine: Machine<unknown>) => {
const u = uMachine.get();
vMachine.update(u);
}
This version should also be flagged for compilation errors since one unknown type may not necessarily align with another unknown type.
Is there a way to communicate this requirement using Typescript?
Edit: It's important that the second version does not compile. I want the compiler to catch any mistakes in this scenario.