Take a look at this code snippet showcasing two extended classes:
interface payloadCollection {
[key: string]: payloadObject<object, object>
}
type payloadObject<TExpectedData extends object = {}, TExpectedResponse extends object = {}> = {
request: TExpectedData,
response: TExpectedResponse
}
class Communicator<
TListeners extends payloadCollection,
TBroadcasters extends payloadCollection
> {
broadcasters!: TBroadcasters;
send<
TMessage extends keyof TBroadcasters,
TData extends TBroadcasters[TMessage]['request'],
TResponse extends TBroadcasters[TMessage]['response']>(message: TMessage, data: TData): TResponse {
return '' as any;
}
addListener<
TMessage extends keyof TListeners,
TData extends TListeners[TMessage]['request'],
TResponse extends TListeners[TMessage]['response']
>(message: TMessage, callback: (data: TData) => TResponse) {}
}
type extendedCommunicatorListeners = {
'extendedListener': payloadObject<{
type: string
}, {
responseType: string
}>;
}
interface extendedCommunicatorBroadcasters extends payloadCollection {
'extendedBroadcaster': payloadObject<{
type: string
}, {
responseType: string
}>
}
class ExtendedCommunicator<
TListeners extends extendedCommunicatorListeners = extendedCommunicatorListeners,
TBroadcasters extends extendedCommunicatorBroadcasters = extendedCommunicatorBroadcasters
>
extends Communicator<TListeners, TBroadcasters> {
private innerMethod() {
/** No typing help here, if I try to ask intellisense for first parameter suggestions, I receive none. However,
* if I introduce the first parameter, the second parameter receives suggestions, and the response type is also correct. */
const response = this.send("extendedBroadcaster", {
type: 'test'
});
}
}
const testExtendedCommunicator: ExtendedCommunicator = new ExtendedCommunicator();
/** No typing help here either, and no error on invalid method */
testExtendedCommunicator.send("invalidMethod", {
invalidData: 15
});
I am attempting to construct a generic class function that accepts parameters based on the parent classes' generic parameters. TypeScript fails to provide suggestions for possible `send` methods and does not report errors when an inappropriate parameter is used in the first method.
Here's a playground link too