在TypeScript中的通用函数中推断映射类型

时间:2017-05-09 20:46:58

标签: generics typescript switch-statement typing inference

this StackOverflow post为例,我实现了一个类型化的事件系统。简化,看起来像:

interface MyTypeMap {
  FOO: string;
  BAR: number;
}

我正在尝试使用此地图创建一个事件处理程序:

function handleEvent<T extends keyof MyTypeMap>(eventKey: T, eventMsg: MyTypeMap[T]) {
  switch(eventKey) {
    case('FOO'):
      // TS believes that eventKey is of type 'never'
      // TS believes that eventMsg is 'string|number'
      break;
    case('BAR'):
      // TS believes that eventKey is of type 'never'
      // TS believes that eventMsg is 'string|number'
      break;
  }
}

在外部调用此函数时,TypeScript的行为与预期一致。例如:

// These work as desired
handleEvent('FOO', 'asdf');
handleEvent('BAR', 5);

// These throw compile errors as desired
handleEvent('FOO', 6);
handleEvent('BAR', 'i am not a string');

然而,在函数TypeScript内部非常困惑。它似乎相信没有任何案件陈述会受到打击。为什么TypeScript无法正确推断函数内部的类型,尽管它可以在外部调用时正常工作?

1 个答案:

答案 0 :(得分:2)

目前无法根据另一个变量的类型约束一个变量的类型。删除T的通用参数handleEvent后,您可以获得最佳效果(不知道为什么它会导致打字稿将eventKey类型推断为never

function handleEvent(eventKey: keyof MyTypeMap, eventMsg: MyTypeMap[typeof eventKey]) {
  switch(eventKey) {
    case ('FOO'):
          const a1 = eventKey; // a1 has type 'FOO'
          const m1 = eventMsg; // m1 has type string|number
      break;
    case('BAR'):
          const a2 = eventKey; // a2 has type 'BAR'
          const m2 = eventMsg; // again, m2 has type string|number
      break;
  }
}

因此,当eventMsg所依赖的变量类型受到限制时,编译器不会限制eventKey的类型。如果可能的话,它会很好。

但是如果您愿意使用将消息类型映射到处理程序而不是switch语句的对象,那么这里是工作原型(目前仅限于每种消息类型只有一个处理程序,但我相信可以轻松扩展):

class Dispatcher {    
    on<
        MessageType extends keyof AppMessageMap
    >(
        messageType: MessageType,
        handler: (message: AppMessageMap[MessageType]) => void
    ): void { 
        this.handlerMap[messageType] = handler;
    }

    handlerMap: {[s: string]: (message: AppMessageMap[keyof AppMessageMap]) => void} = {};

    emit<MessageType extends keyof AppMessageMap>(messageType: MessageType, message: AppMessageMap[MessageType]) {
        const handler = this.handlerMap[messageType];
        if (handler) {
            handler(message);
        }
    } 
}

/* messages.ts */

interface AddCommentMessage {
    commentId: number;
    comment: string;
    userId: number;
}

interface PostPictureMessage {
    pictureId: number;
    userId: number;
}

interface AppMessageMap {
    "ADD_COMMENT": AddCommentMessage,
    "POST_PICTURE": PostPictureMessage
}

/* app.ts */
const dispatcher = new Dispatcher();


dispatcher.on("ADD_COMMENT", (message) => {
    console.log(`add comment: ${message.comment}`);
});
dispatcher.on("POST_PICTURE", (message) => {
    console.log(`post picture: ${message.pictureId}`);
}); 

dispatcher.emit('ADD_COMMENT', {
    comment: 'some comment',
    commentId: 2,
    userId: 3
});
dispatcher.emit('POST_PICTURE', {
    pictureId: 4,
    userId: 5
});