TypeScript高级类型检查

时间:2018-07-14 09:40:51

标签: typescript

请检查代码中的注释。能否获得我想要的东西,或者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);

感谢您的回答!

1 个答案:

答案 0 :(得分:0)

您可以使用通用类型来保存键的类型,并可以使用类型查询来指定参数必须与字段类型相同:

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<K extends keyof HandlersRegistry>(eventType: K, handler: HandlersRegistry[K]) {
    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);
// show error as expected
addToRegistry('test', authHandler);