【发布时间】:2018-07-14 18:26:49
【问题描述】:
请检查代码中的 cmets。能不能得到我想要的东西还是TS没有这个功能?
我需要对 addToRegistry 函数进行类型检查。
TypeScript playground with code
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);
感谢您的回答!
【问题讨论】:
标签: typescript