Seeking assistance with adding constraints to generics in a signature. The current setup is functioning well.
Interested in implementing constraints based on the types of another type.
async publish<T>(exchange: Exchange, routingKey: RoutingKey, message: T, options?: amqplib.Options.Publish) {
return this.amqpConnection.publish(exchange, routingKey, message, options)
}
Specifically looking to apply constraints on RoutingKey and "T". The constraint for "T" should be dependent on the specified RoutingKey.
Additionally, the RoutingKey should be influenced by the selected Exchange.
Here are examples of some types:
// Two types of exchanges.
export enum Exchange {
BscDexPancakeswap = "bsc-dex-pancakeswap",
PolygonQuickwap = "polygon-dex-quickswap",
}
export enum RoutingKey {
PendingTx = "pending-tx", // applicable to all Exchanges
PendingTxHash = "pending-tx-hash", // applicable to all Exchanges
BridgeChain = "bridge-chain", // only valid when Exchange is set to PolygonQuickswap
}
// The "T" being passed into publish
export interface TxHashMsg { // valid for any Routing Key
txHash: string
}
export interface TxMsg { // valid for any Routing Key
tx: string
}
export interface BridgeMsg { // only valid for Routing Key = BridgeChain
bridgeId: string
}
Essentially, incorrect routingKey should trigger a type error
this.messageBrokerService.publish<BridgeMsg>(Exchange.BscDexPancakeswap, RoutingKey.PendingTx, tx)
Similarly, an error should be thrown when the Exchange is incorrect
this.messageBrokerService.publish<BridgeMsg>(Exchange.BscDexPancakeswap, RoutingKey.BridgeChain, tx)
Valid usage: correct Exchange, correct RoutingKey, and correct Message that adhere to the defined constraints.
this.messageBrokerService.publish<BridgeMsg>(Exchange.PolygonQuickwap, RoutingKey.BridgeChain, tx)
This is a complex issue, looking for advice on feasibility and ease of implementation.
Thank you in advance