Could you please review the comments in the code? I am trying to determine if it is feasible to achieve what I need or if TypeScript does not support such functionality.
I require type checks for my addToRegistry
function.
Play around with TypeScript in this interactive environment
type MessageHandler<T> = ((data: T) => void) | ((data: T) => Promise<void>);
interface AuthPayload {
id: string;
}
class HandlersRegistry {
auth?: MessageHandler<AuthPayload>;
test?: MessageHandler<number>;
}
const registry = new HandlersRegistry();
// handler type should ref on HandlersRegistry[key] by eventType
// function addToRegistry<T>(eventType: keyof HandlersRegistry, handler: ???) {
function addToRegistry<T>(eventType: keyof HandlersRegistry, handler: MessageHandler<T>) {
registry[eventType] = handler; // should not be an error
}
const authHandler: MessageHandler<AuthPayload> = (data: AuthPayload) => null;
// correct
addToRegistry('auth', authHandler);
// correct, shows error, but I don't want to provide type of payload every time
addToRegistry<number>('test', authHandler);
// should show error, but doesn't
addToRegistry('test', authHandler);
Thank you for your responses!